Win a copy of Head First Android this week in the Android forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

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: 22507
122
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