File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the use of Clonable interface?

 
sujitha reddy
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of Clonable interface? Clone method is in Object class,while we are using Clone method we must implement clonable interface, why?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64178
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please reserve this forum for advanced questions. I have moved this to the intermediate forum.
 
Nav Letha
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or why not?
Cloneable is an interface and you need to implement it if you want to clone the object.Object's clone method only gives you basic implementation.

you can verify if an object implements Cloneable by using 'instanceof'.

If you dont implement Cloneable, it will throw CloneNotSupportedException.

side note:Note that object's clone does shallow copy meaning if you have a complex member, it will copy only referrence and it is your responsibility (if situation demands it) to do deep copy.
 
Ken Blair
Ranch Hand
Posts: 1078
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sujitha reddy:
what is the use of Clonable interface? Clone method is in Object class,while we are using Clone method we must implement clonable interface, why?


It's called a marker interface and is widely considered an anti-pattern. Why the original designers decided to use a marker interface I'm not sure. In fact there's an RFE in Sun's bug database with a suggested mechanism to replace Cloneable:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5101827
 
Ken Blair
Ranch Hand
Posts: 1078
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nav Letha:
Or why not?


How about the fact that it's an interface that doesn't actually declare the method it's defining the behavior for? Object declaring a method that may or may not actually be implemented is another absurdity arising from it. Unfortunately this sad fact also results in an exception that must be declared since a subclass may or may not actually be Cloneable and if that's not bad enough it's a checked exception. While not caused by the use of a marker interface, it's also problematic that it relies on what are essentially undocumented conventions.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic