Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does inheritance work underneath?

 
Mike Stach
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a basic question related to inheritance.
Consider the following code snippet:

public class B {
}

public class D extends class B{
public D(){
super();
}

public static void main(String args[]){
new D();
}
}

My question is whether new D() invocation will create 3 objects i.e. D, B, and top class Object or whether it will create only 1 object i.e. D?

I am confused as to whether inheritance leads to chained object creation or whether the compiler copies all the eligible public and protected members from the base class into the derived class so that base class does not need to be instantiated all the time.

When I see the bytecode, it looks like 3 objects are created because of init() invocations but I just wanted to be sure about it. I would appreciate if someone could comment on it.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the confusion is because the super class constructors are called. Only one object(the final one in the inheritance tree) is created. It would be better if you could try to understand the "IS-A" relationship. When you create a 'Dog' you are also creating an 'Animal', because Dog is an Animal. You are creating a SINGLE object that is instance of both a sub and superclass.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Horse Rider, welcome to JavaRanch. Please check your private messages for an administrative matter. You can see them by clicking My Private Messages.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Horse Rider:

I am confused as to whether inheritance leads to chained object creation or whether the compiler copies all the eligible public and protected members from the base class into the derived class so that base class does not need to be instantiated all the time.


Neither the first nor the second.

It's the Virtual Machine that, at object creation time, will create *one* object that has all the members of the whole class hierarchy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic