| Author |
Will class casting creats new object on the heap?
|
zhong chen
Greenhorn
Joined: Oct 12, 2009
Posts: 24
|
|
If B extends A and you do:
A a = new B();
B b = (B)a;
will it creates two objects?
|
 |
Guillaume Jeudy
Greenhorn
Joined: Jul 27, 2009
Posts: 24
|
|
|
The answer is no, an object is only really created when you use the new keyword. In your example 1 object is created and placed on the heap.
|
SCJP 1.4 and 6.0, SCJD
|
 |
Atwal Usha
Ranch Hand
Joined: Sep 10, 2009
Posts: 137
|
|
Well, Jeudy has already explained it. Class casting never creates objects on heap it's the new keyword which is responsible for that. You could check that by executing the following code.
When Line 1 is executed the constructor of the Child class executes and displays the output child object however the same is not true for Line 2 which means the casting has not created another object on heap. Hope it helps.
|
Java Certification Exam Mock Tests: SCJA SCJP 5 SCJP 6 SCJP 6 (Online Training) SCJP 6 (Instructor Led Training) SCWCD 5 SCBCD 5 SCEA 5
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
When you cast something, what it means is that you say to the compiler: "Compiler, I have a variable of type A here, but I want you to treat it as if it is of type B. (Because I know that the variable really refers to an object of type B)."
Casting does not create any objects or do any smart conversions.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Prithvi Sehgal
Ranch Hand
Joined: Oct 13, 2009
Posts: 771
|
|
Yes, only object will be created basically and i believe there will be now two reference variables on the stack
referring to the same object.
Cheers,
|
Prithvi/Beenish,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
|
 |
Nitish Bangera
Ranch Hand
Joined: Jul 15, 2009
Posts: 536
|
|
|
The main thing to remember for this is for what reason the casting is done and for whoom is it for the compiler or is it used during running the program.
|
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
|
 |
 |
|
|
subject: Will class casting creats new object on the heap?
|
|
|