charliemango
charliemango

Reputation: 85

Overriding a method that is called from a constructor

If an instance of subclass is created, the output is sub0 sub2

Two questions on this:

Example:

class Superclass{
   int i = 1;

    Superclass(){
      aMethod();
    }
   void aMethod(){
      System.out.println("super" + i);
   }
}

class Subclass extends Superclass{
   int i = 2;

   Subclass(){
   aMethod();
   }

   void aMethod(){
      System.out.println("sub" + i);
   }
}

Upvotes: 2

Views: 113

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213391

Why is the subclass method called even though the superclass constructor is not finished?

Because the instance of subclass is already created at that point of time. The super class constructor is just called to initialize the state of the object. Now, since the instance is actually that of a subclass (I assume you are talking about this case only), the actual method invoked will be the overridden one (the method overriding rules apply here).

And why is the instance field not initialized when called from the superclass constructor (the sub0 output)?

Because, the subclass constructor has not yet started the initialization part. It's the super class constructor that is executed first. So, if the overridden method in subclass is called from the super class constructor, the fields of the subclass hasn't been initialized yet and the value of i is still 0.

See also:

Upvotes: 7

Related Questions