File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Will class casting creats new object on the heap?

 
zhong chen
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If B extends A and you do:
A a = new B();
B b = (B)a;

will it creates two objects?
 
Guillaume Jeudy
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Atwal Usha
Ranch Hand
Posts: 137
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic