Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: new, inheritance and objects number

I am trying to understand how inheritance is realized inside JVM. It seems to me, that if we have the following code:

class A {
  int aa;
}

class B extends A{
   int bb;
}
....
B b=new B();

Inside the JVM three objects will be created:

  1. object of B (with field int bb),
  2. object of A (with field int aa)
  3. object of Object.

Of course the programmers see only one object of class B. Am I right? Or is only one object created inside JVM?

What I think:

The new returns the reference to B. Why I think so is (for example) that if we override some method from A in B we can always get it using super. Besides in default constructor B the first line will be call to default constructor A in which we can call the constructor on certain object ONLY IF this object exists. Therefore a separate A object exists?


1 Answers

At first, the spec says that the internal structure of objects is not specified, so in theory, a JVM could internally create more than one object, where B contains only fields new to B, and a link to an A object, which contains the fields of A.

It also says something about the Oracle JVM implementation: A class instance contains three pointers. One to a method table, one to some space in heap where the data of the instances fields is, and one the Class object that instance belongs to.

You can conclude from that, that there is only one instance per object created, namely the instance of B. The method table for this instance contains all methods from B, A and Object, as well as the heap space contains all data from fields from B, A (and Object).

like image 90
Alex Avatar answered Sep 03 '26 10:09

Alex