YouTrack 2.0
The moose likes Beginning Java and the fly likes Inheritance - how many objects created??? The Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Inheritance - how many objects created???" Watch "Inheritance - how many objects created???" New topic
Author

Inheritance - how many objects created???

Imran Mehrenali
Greenhorn

Joined: Feb 26, 2007
Posts: 6



1) In the above code, when i create an object of Class B, how many objects will get created? Only one object of class B that has 2 members (a and b) or two objects - one of class A that has one member (a), and another of class B that also has only member (b) but can directly acccess the member (a) beloning to object of class A.

2) I was about to ask how many constructors will be called, but have tried this out myself in a java program and have found that 2 constructors (A() and B()) are called while creating an object of class B.
Does this mean that 2 objects are created.

Many Thanks.
[ October 29, 2007: Message edited by: Imran M ]
Ernest Friedman-Hill
author
Sheriff

Joined: Jul 08, 2003
Posts: 21809
I'm going to assume you meant to have class B extend class A in the above; otherwise the question doesn't make sense.

The answer is just one object. An instance of B includes an A "part". Imagine a piece of paper 1 inch square, call it A. Then think of a B object as a piece of paper 2 inches square, with a 1-inch square drawn onto it labeled "A". The A constructor is called to initialize the A part of the single B object.

[Jess in Action][My Art][AskingGoodQuestions]
Imran Mehrenali
Greenhorn

Joined: Feb 26, 2007
Posts: 6
edited the code. Original Post now reflects the right code. Apologies for the incorrect code.
Jesper Young
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 8683
"Imran M", please check your private messages. You can see them by clicking My Private Messages.

Java Beginners FAQ - JavaRanch SCJP FAQ
The Java Tutorial - Java SE 6.0 API documentation
 
aspose file troubles
 
subject: Inheritance - how many objects created???
 
JProfiler
Get rid of your performance problems and memory leaks!