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

When and why to use Cloneable interface in java?

 
anish jain
Ranch Hand
Posts: 129
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the use of cloning in Java? When we have to make clone of the object?
 
Sudheer Maddukuri
Greenhorn
Posts: 6
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.

The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.

Why create a local copy?

The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.
 
Sudheer Maddukuri
Greenhorn
Posts: 6
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The cloning mechanism is also an implementation of prototype design pattern which is defined as :

The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic