• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Peter Rooke
  • Himai Minh
Bartenders:
  • Piet Souris
  • Mikalai Zaikin

Object cast in Prototype pattern

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 22743
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
vitesse wei
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, Saloon.
 
reply
    Bookmark Topic Watch Topic
  • New Topic