Java seems inconsistent in how class constructors and methods deal with inheritance.
Case 1 - Methods:
public class HelloWorld { public static void main(String[] args) { Bee b = new Bee(); b.foo(); } } class Insect { public void foo() { this.bar(); System.out.println("Insect foo"); } public void bar() { System.out.println("Insect bar"); } } class Bee extends Insect { @Override public void foo() { super.foo(); System.out.println("Bee foo"); } @Override public void bar() { System.out.println("Bee bar"); } }
The above code outputs the following:
Bee bar
Insect foo
Bee foo
Note that a call to the this.bar () method in the Insect foo () method does return and calls the Bee bar () method (instead of calling the Insect bar () method).
Case 2 - Constructors:
public class HelloWorld { public static void main(String[] args) { Bee i = new Bee(1); } } class Insect { public Insect(int size) { this(size, 123); System.out.println("Constructor: Insect size"); } public Insect(int size, int height) { System.out.println("Constructor: Insect size, height"); } } class Bee extends Insect { public Bee(int size) { super(size); System.out.println("Constructor: Bee size"); } public Bee(int size, int height) { super(size, height); System.out.println("Constructor: Bee size, height"); } }
The above outputs the following.
Constructor: insect size, height
Constructor: insect size
Constructor: bee size
Note the call to "this (size, 123);" in the Insect constructor goes to the second Insect constructor instead of the bee 2nd constructor.
So, in the end, method calls return to the subclass, and constructor calls remain in the superclass. Can someone explain why?
source share