• Post Reply Bookmark Topic Watch Topic
  • New Topic

super class instantiation

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {

''
}

class Sub extends A {

..
}

*************

When I do

Sub sub = new Sub();

Does JVM automatically also create an instance of class A ? By rule, it automatically calls super class' constructor, so it seems it should also create an instance of A in addition to an instance of "Sub". So it creates two different instances in memory after I do "Sub sub = new Sub()" ?

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An instance of Sub contains an instance of A, like a mango contains a pit. They're not separate objects.
 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:An instance of Sub contains an instance of A, like a mango contains a pit. They're not separate objects.


Please be more specific if you don't mind --

1. So there is only ONE object got created, right ?

2. What do you mean "object of Sub contains an instance of A" ? A is not a class variable of Sub, how does it "contain" ? Does "sub" object contain a reference to "A" ? wait, since there is not a separate object creatd for A, there should not be such reference at all. So what do you mean by "contain an instance of A". Please help clarify.

Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I said before, a "Sub" contains an "A" exactly the way a mango contains a pit. The pit is part of the mango; it's inside. There's a part of the mango you can call "the pit", but in reality it's it's all one object, the mango including the pit.

1) Yes, one object.
2) Imagine that "Sub" declares one "int" member variable, and "A" has one "int" member variable. Then an instance of "Sub" is the size of two "int" member variables. Part of the memory that makes up the Sub object is taken up by the "A" part -- one of the ints.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!