0

For Example consider three classes A,B and C. B extends A and C extends B. Now class C has all the accessible methods and fields of B.

When an instance of C is created as ----- C c = new C(), Heap area is allocated for the instance fields in 'C' (Does it includes properties of 'A' and 'B' also ?). When the super class constructor is called, a new object of super class must be created. Where is the reference to this object stored ?

How is the class hierarchy managed when a class object is instantiated ?

Kranthi
  • 133
  • 2
  • 10
  • 1
    There are not _separate_ objects. The `C` object _is also_ a `B` and _is also_ an `A`. There is only one reference, to only one object. – Louis Wasserman Dec 12 '17 at 18:42
  • https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html – sForSujit Dec 12 '17 at 18:48
  • actually C has all methods and fields of B and A; not only he accessible ones, despite the code of C not necessarely has access to all of them. As Louis wrote, C is an (extension) of B and A, like a car is also a vehicle which is an object. – user85421 Dec 12 '17 at 18:55
  • Thanks for that. Then where are the private fields of super class stored. I hope they cannot be stored in the same object as they are not accessible. – Kranthi Dec 12 '17 at 18:56
  • Also in case of hidden fields - how can two fields with the same be stored in the same object ? – Kranthi Dec 12 '17 at 19:03
  • Private fields and methods are not accessible from the object. If you have same named methods, then you will need to use @override and then it will call the overridden method. – clinomaniac Dec 12 '17 at 19:05
  • Thanks for that Louis Wasserman. My other questions are: 1.Then where are the private fields of super class stored. I hope they cannot be stored in the same object as they are not accessible ? 2.Also in case of hidden fields - how can two fields with the same be stored in the same object ? – Kranthi Dec 12 '17 at 19:07

1 Answers1

1

The (one) new instance will have heap space allocated for the fields of all three classes. Calling super-class constructors does not create new instances, it only initializes fields.

Steve11235
  • 2,849
  • 1
  • 17
  • 18