This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Base b=new Derived(); Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Base b=new Derived();" Watch "Base b=new Derived();" New topic
Author

Base b=new Derived();

Vaibhav Shridish
Greenhorn

Joined: Jun 06, 2002
Posts: 28
Are these statements the same (the inheritance
heirarchy is self explainatory)?
Statement 1)
============
Base b=new Base()
Derived d=new Derived();
b=d;
Statement 2)
============
Base b=new Derived();
Now in the above statement-2 which object does b
refers to Base or Derived ?
Thanks in advance


Vaibhav Shridish
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
b would refer to a Derived object (in both cases).
Corey


SCJP Tipline, etc.
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Originally posted by Vaibhav Shridish:
Are these statements the same (the inheritance
heirarchy is self explainatory)?

Well, almost but not quite the same.

Statement 1)
============
Base b=new Base()
Derived d=new Derived();
b=d;

The above code actually creates two objects, a Base, and a Derived. After the line "b=d" is called, the Base object reference is lost and becomes eligible for garbage collection, and you end up with a Base reference variable pointing to a Derived object.


Statement 2)
============
Base b=new Derived();
Now in the above statement-2 which object does b
refers to Base or Derived ?

Well, clearly you are creating a Derived, and assigning it to a reference variable of type Base; since Base is a superclass of Derived, this is legal (and the quintessential example of polymorphic assignment.) Unlike the first example though, you are NOT creating a Base object.
[ June 06, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Base b=new Derived();