-1

I know how objects store in the Heap. But what about inherited objects

public class A {
  private int id;
  public A(int id){
    this.id=id;
  }
}

public class B extends A {
  private String name;
  public B(int id, String name){
    super(id);
    this.name=name;
  }
}

if we create an object like B b = new B(1, "b"); how this object store in the Heap.

I mean JVM store object A class and B class also

  • Class objects are different from instances, i.e. they are stored elsewhere (at least used to be). An instance of B will just be stored the same way as instances of A, i.e. it will take a block of memory that holds the value of `id` and the reference `name` (not the value). – Thomas Jan 11 '23 at 15:02
  • I'm sure this is totally depending on the implementation of the JVM. Any reason you need that information? – cyberbrain Jan 11 '23 at 15:03

1 Answers1

2

In memory, an instance of class A consists of:

  1. An object header
  2. values of the fields of class A, i.e., int id;

In memory, an instance of class B consists of:

  1. An object header
  2. values of the fields of class A
  3. values of the additional fields of class B, i.e., String name;

This arrangement ensures that a reference to class B, which is a pointer to the object header in memory, is also a valid reference to class A -- the is-a relationship you declared with the extends keyword is implemented this way.

This is fundamentally why you can only have one base class.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • My understanding is that multiple inheritance was disallowed in Java because the Diamond Problem causes such classes to be too complex to reason about, not (primarily) because of the resulting memory layout. (Though, disallowing it does indeed make the layout simpler.) – BambooleanLogic Jan 11 '23 at 15:16
  • 1
    When Java was invented, we already had multiple inheritance in C++, and a fair bit of experience demonstrating that it created classes that were indeed difficult to reason about... but "reasoning about" those classes included a lot of issues related to memory layout and pointer translation, and the consequences of that, because Java was intended to be a performant language. Without performance concerns, it's not difficult to design a system for multiple inheritance that works reasonably. – Matt Timmermans Jan 11 '23 at 15:38