aspose file tools
The moose likes Java in General and the fly likes Object cast in Prototype pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Object cast in Prototype pattern" Watch "Object cast in Prototype pattern" New topic
Author

Object cast in Prototype pattern

vitesse wei
Ranch Hand

Joined: Sep 07, 2007
Posts: 100
I just go through the prototype pattern with a shallow clone implementation,code as bellow:



in Clone method,we call super.clone(),that return a Object,this Object is not a Product and we know that Product is a Object,how can we cast the Object to Product in main body without error?,
thanks ranchers


SCJP 5.0<br />SCWCD1.4<br />SCBCD5
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

vitesse wei wrote:in Clone method,we call super.clone(),that return a Object,this Object is not a Product and we know that Product is a Object,how can we cast the Object to Product in main body without error?,
thanks ranchers

Object.clone() returns an object of the current type. Since Product overrides Object, super.clone() does return a Product instance, it's only the reference that's Object. Your code should compile just fine. Alternatively, using a covariant return type (available since Java 5.0), you move the cast to the method:
Just two notes:
1) The clone will share the same array instance. The reference is copied, not the array itself. Modifying the content of p1.data will modify p2.data as well.
2) Calling toString() on an array produces a String that's usually not very useful. java.util.Arrays.toString(p1.data) will return a more readable String.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
vitesse wei
Ranch Hand

Joined: Sep 07, 2007
Posts: 100
Thanks, Saloon.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Object cast in Prototype pattern
 
Similar Threads
clone() not visible ??
clone()
question about Prototype patterns
I am getting clone() has protected access in java.lang.Object
Please help - cloaning members within a superclass and class.