2

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?

1 Answer 1

7

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.