• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Clone()

Object Cloning in Java

July 4, 2012 By j2eereference Leave a Comment

OBJECT CLONING:

Object cloning is for creating an exact copy of an object, not just creating a new reference variable pointing to it.
The modifications made to the cloned object do not affect the original object whatsoever.
The object.clone() method described below is used for this purpose.

Why cloning?

We know that cloning is the way to create the copy of another object. If we need to create the object similar to the existing one, we can do it by using  new keyword and then doing the properties settings , but  it will take lots of time for processing , like setting values to the variables. Here comes the benefit of cloning method .Cloning overcome all these and it is very easy to make a copy of object.

Uses:

The clone() method is  defined in the Object class, this method  used to create a local copy of an object in the obvious event of us wanting to modify the object without modifying the method callers object.

Here are a couple of things you must keep in mind while cloning an object:

  • Each class you wish to clone must implement the “Cloneable” interface.

In case it doesn’t, the clone method will throw a “CloneNotSupportedException“.

This interface does not contain any methods.It is just a marker interface.

  • The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.
  • The default implementation of Object.clone() performs a shallow copy.

 When a class desires a deep copy (Deep copy means if your object contains references of other objects or  collections.)or some other custom behavior,  they must perform that in their own clone() method after they obtain the copy from the superclass.

  • The return type of clone() method is Object, and needs to be explicitly cast back into the appropriate type.
  • Most interfaces and abstract classes in Java do not specify a public clone() method.

           As a result, often the only way to use the clone() method is if you know the actual class of an object.

  • Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves.

 

Example for Object Cloning:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.j2eereference.coreJave;
 
public class BookClone implements Cloneable{
 
  private String name;
  private int cost;
 
  public BookClone(String name, int cost){
  this.name = name;
  this.cost=cost;
  }
 
  public Object clone(){
  try{
      BookClone cloned = (BookClone)super.clone();
      return cloned;
  }
  catch(CloneNotSupportedException e){
  System.out.println(e);
  return null;
  }
  }
 
  public String toString(){
  return "[name=" + name+ ",cost=" + cost+ "]";
  }
 
  public static void main(String[] args){
 
  BookClone book = new BookClone("Java for Dummies", 500);
  BookClone book1 = (BookClone)book.clone();
  System.out.println("BookCloneOriginal=" + book);
  System.out.println("ClonedCopy=" + book1);
  }
 
}

Output:
BookCloneOriginal=[name=Java for Dummies,cost=500]
ClonedCopy=[name=Java for Dummies,cost=500]

 

 

Related Posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof

Filed Under: Core Java Tagged With: Clone(), Java Clone, Object cloning

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.