Two Laptop Bag*
The moose likes Beginning Java and the fly likes super class instantiation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "super class instantiation" Watch "super class instantiation" New topic
Author

super class instantiation

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

An instance of Sub contains an instance of A, like a mango contains a pit. They're not separate objects.


[Jess in Action][AskingGoodQuestions]
Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.
 
Don't get me started about those stupid light bulbs.
 
subject: super class instantiation
 
Similar Threads
overriding/loading
help: error: cannot find symbol
why constructors
Inner Class Constuctors
Inner Classes Constructors