Java: How constructors and methods behave with inheritance

Viewed 251

Java seems to be 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

Notice the call to "this.bar()" in Insect's foo() method actually goes back and calls Bee's bar() method (instead of calling Insect's 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

Notice the call to "this(size, 123);" in Insect's constructor goes to Insect's 2nd constructor instead of bee's 2nd constructor.

So in summary, method calls go back to the subclass while constructor calls stay in the superclass. Can anyone explain why?

1 Answers
Related