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
posted
0
b would refer to a Derived object (in both cases). Corey
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.