Super class in pkg1:
Sub class in pkg2:
Main class for testing in pkg3:
Output:
in super private method1
in sub public method2
in super private method3
in super public method4
in super package-private method5
in sub private method1
in sub public method2
in sub public method3
in super public method4
Some points about inheritance and override in Java:
- Only public or protected members can be overridden. In above test code, Line 21 in SubClass.java will break if commented out.
- If moving SubClass and SuperClass to the same package, Line 21 in SubClass.java will work since default access scope is package-private.
- private or package-private members cannot be overridden. Even they have definitions with same signature, they are different methods and overriding rules and resolution don't apply to them.
- If calling in subclass, even with super, JVM will try to locate overriding members in subclass. Again, this happens only when the member is declared as public or protected.
No comments:
Post a Comment