1

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?

Davis Broda
  • 4,102
  • 5
  • 23
  • 37
paidedly
  • 1,413
  • 1
  • 13
  • 22
  • 3
    But there _is_ an instance of `A`. It just happens to also be an instance of `B`. – Dawood ibn Kareem Mar 24 '15 at 18:41
  • I'm voting to close this question as off-topic because answering this question displays a lack of basic knowledge of OO principles and should be taught by reading a good tutorial since it's too broad to answer on SO. https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html – Jeroen Vannevel Mar 24 '15 at 18:45

2 Answers2

5

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

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.

Community
  • 1
  • 1
S. Pauk
  • 5,208
  • 4
  • 31
  • 41
  • so even without an instance of A in memory, the field b with value 5 is residing in memory? – paidedly Mar 24 '15 at 18:53
  • do you mean an instance of B? – S. Pauk Mar 24 '15 at 18:54
  • the instance variable b defined in class A.Is it present in memory even though there is no instance of A in memory? – paidedly Mar 24 '15 at 18:55
  • when you instantiate B private field b is also created in memory – S. Pauk Mar 24 '15 at 18:58
  • ok.so private variables of superclass are not inherited by subclass but are inherited by instances of subclass? Is this statement correct? – paidedly Mar 24 '15 at 19:07
  • 1
    Have you checked the link? When you talk about class inheritance then `does not inherit` means `is not visible/cannot be accessed`. When you talk about object inheritance it means that parent's fields are also created in memory (inherited). – S. Pauk Mar 24 '15 at 19:11