| 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.
|
 |
 |
|
|
subject: Object cast in Prototype pattern
|
|
|