Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Object Cloning in Java

    Object cloning in Java refers to the process of creating an exact duplicate of an object. To achieve this, Java provides the clone() method within the Object class.

    For an object to be eligible for cloning, its respective class must implement the Cloneable interface. If Cloneable interface is not implemented, calling the clone() method will result in a CloneNotSupportedException.

    In Java, the reference to the object is copied, rather than the object itself. This means that both the original object and the newly assigned reference point to the same object in memory.

Table Of Content

  • Object cloning in Java
  • Example of Object cloning
  • Creating a copy of object using the clone() method
  • Deep Copy and Shallow Copy
  • Advantages of clone method
  • Disadvantages of Object cloning






Example of Object cloning with assignment operator


Java example of Object cloning with assignment operator
 // Java example of Object cloning with assignment operator
class Car{
	int speed;
	public Car() {
		// TODO Auto-generated constructor stub
		speed=100;
	}
}

class Main {
	public static void main(String[] args){
		Car car=new Car();
		System.out.println(car.speed);
		
		Car car2=car;
		car2.speed=150;
		
		System.out.println(car.speed);  //changes made in car2 reflect back to car object
		System.out.println(car2.speed);
		
	}
}




Output:

100 
150 
150 

Creating a copy of object using the clone() method

  • In order to acquire the reference to the duplicated object, any class that incorporates the clone() method must invoke super.clone().
  • Additionally, the class needs to implement java.lang.Cloneable. This will result in the throwing of CloneNotSupportedException if the clone() method is invoked on an object of that class before generating a clone of the object's Cloneable interface.

protected Object clone() throws CloneNotSupportedException  





clone() method


Java example of clone() method
 // Java example of clone() method
class Vehicles{
	int speed;
	public Vehicles() {
		speed=100;
	}
}
class Car implements Cloneable {
	int speed;
	public Car() {
		speed=90;
	}
	Vehicles vehicles = new Vehicles();
    public Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}

class Main {
	public static void main(String[] args) throws CloneNotSupportedException{
		Car car=new Car();	
		Car car2=(Car)car.clone();
		car2.vehicles.speed=150;  // value of speed is changed to 150
		
		System.out.println(car.speed);  // change in speed value is not reflected
		System.out.println(car2.vehicles.speed);
		
	}
}



Output:

90  
150   


Deep Copy and Shallow Copy

  • Shallow copy : The technique for copying an object that is used by cloning by default is shallow copy. This method copies the fields of an old object A to a new object B. The object V will point to the same location as object A pointed out because the reference is copied to B while copying the object type field. It copies the value of the primitive type if the field value is one.
  • As a result, any modifications made to objects that are references in objects A or B will be reflected in other objects.



  • Deep Copy when using the clone() method : If we want to make a deep copy of object A and put it in a new object B, we must also make a new copy of any fields that refer to object A and put them in object Y. This means that any changes made to referenced object fields in object A or B will only affect that object and not the other.
  • All fields and the memory that the fields point to that is dynamically allocated are duplicated during a deep copy. A deep copy happens when an object and the objects it refers to are both copied.






Advantages of clone method:

  • A new copy of the object won't be created if we use the assignment operator to assign an object reference to another reference variable because it will point to the same address location as the original object. The original object will therefore be updated whenever the reference variable changes.
  • When employing a copy constructor, it's necessary to manually copy all the data, which entails reassigning all fields of the class within the constructor. On the other hand, the clone method independently handles all the steps required to create a new copy. So we use use object cloning to avoide extra processing.
  • The clone() method provides the quick way for duplicating an object.





Disadvantages of Object cloning

  • In order to use the Object.clone() method, we must make several changes to our code, such as implementing the Cloneable interface, defining the clone() method, handling the CloneNotSupportedException, and finally calling Object.clone(), among other things.
  • Despite the absence of any methods, we must implement a cloneable interface. We simply need to use it to inform the JVM that our object is capable of being cloned.
  • Even in the absence of specific methods, it's necessary to implement a cloneable interface. This informs the Java Virtual Machine (JVM) that our object can be cloned. Since the method Object.clone() is protected, we must create our own clone() method and indirectly invoke Object.clone() within it.
  • In cases where a subclass requires a clone method, all its parent classes, including their superclasses, must either internally define the clone() method or inherit it from another parent class. Failing this, the chain of super.clone() calls will not work.
  • It's important to note that Object.clone() only supports shallow copying. If a more thorough deep cloning is needed, then we must override this method.
  • It's worth mentioning that Object.clone() doesn't invoke any constructors. As a result, we have limited control over how an object is instantiated during the cloning process.
Java Wrapper classes Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.