Knight
Knight

Reputation: 573

Java abstract class constructor

I'm wondering what is happening here:

I have abstract superclass

public abstract class Superclass {
  public Superclass()
  {
        doSth();
  }
  public abstract void doSth();
}

And subclass

public class Subclass extends Superclass{
   private int x = 10;
   public void doSth()
   {
      System.out.println("Value x="+this.x);        
   }    
}

When I make

Subclass x= new Subclass();
x.doSth();

I get:

Value x=0
Value x=10

I don't know why first I get x=0 (why not x=10 from the start?) and then x=10?

Upvotes: 2

Views: 92

Answers (1)

Eran
Eran

Reputation: 394156

The constructor of the super-class is executed before the isntance initializer expressions of the sub-class, which is why x still has the default value of 0 in the first call to doSth(). The second call x.doSth() takes places after the Subclass instance is fully initialized, so x contains 10.

More details :

When you call the constrcutor of Subclass, first it calls the constructor of Superclass which calls the constructor of Object. Then the body of the Superclass constructor is executed, so doSth() is executed. Only after the Superclass constructor is done, the instance initialization expressions of Subclass (in your case, the assignment x = 10; are evaluated. Before they are evaluated, x still contains the default value - 0, which is the value you see printed by the first call to doSth().

Upvotes: 7

Related Questions