paidedly
paidedly

Reputation: 1413

How is constructor being called without any instance associated with it?

Please see the below code:

class A {
    private int b;
    A(){
        b=5;
    }
}

class B extends A {

}

class C {
    public static void main(String args[]){
        B b=new B();
    }
}

When I create an instance of B,the default constructor of B invokes the constructor of A which assigns a value to instance variable b. My query is since instance variables are associated with instances of classes, and we have not created any instance of class A,what does this assignment(b=5) really mean? Also what does the call to A's constructor really mean when there is no instance of A?

Upvotes: 1

Views: 57

Answers (2)

S. Pauk
S. Pauk

Reputation: 5318

Check this discussion about class inheritance vs object inheritance in Java. According to JLS you would say that class B doesn't inherit the private field b from class A.

Members of a class that are declared private are not inherited by subclasses of that class.

However an instance of B inherits all the data from A including the private field b.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198033

B extends A means that an instance of B is also an instance of A, just like a dog is also an animal. It's both at the same time, so it's perfectly normal for b=5 to make sense, since the B is also an A and that is initializing the b field in A.

Upvotes: 5

Related Questions