silvermaze
silvermaze

Reputation: 153

Upcasting; why do i get the output 11

So i ran this code and I don't understand why I got the output 11:

class Parent{
   protected int counter;
   public Parent(){counter++;}
}

class Child extends Parent{
   public Child(){
     System.out.print(counter);}
  }
}
public class Test{
   public static void main(String [] args){
      Parent p = new Child();
      System.out.print(p.counter);
   }
}

Upvotes: 0

Views: 30

Answers (1)

Thiyagu
Thiyagu

Reputation: 17890

Parent p = new Child();

This creates an instance of the Child class. This must execute the Child class's construcutor. But before that it will run the Parent class's constructor. This will set the value of counter as 1.

Next, when the child class constructor is run, it prints 1.

The last part is trivial. Calling System.out.print(p.counter); prints another 1. Thus, the result is 11.

Summary: Parent class's constructor will be executed before the child's.


Btw, this doesn't have anything to do with upcasting. It is inheritance.

Upvotes: 2

Related Questions