Saturday, July 6, 2013

Inheritance and Override in Java

Some learning and testing code on Java class inheritance and member override.

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:
  1. Only public or protected members can be overridden. In above test code, Line 21 in SubClass.java will break if commented out.
  2. If moving SubClass and SuperClass to the same package, Line 21 in SubClass.java will work since default access scope is package-private.
  3. 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.
  4. 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