All Courses
Clone Objects in Java

Java Clone Object

April 30th, 2019 Java

Java Clone Object:

Object Cloning in Java

Creating a copy of an object. Method clone() in Object class is used to clone an object. No need to write repetitive & lengthy codes and also its most efficient & easiest way for copying objects.

Syntax

protected Object clone() throws CloneNotSupportedException

Program:

class Vehicle implements Cloneable {
int modelyear=0;
String modelname = “”;
Vehicle(String modelname , int modelyear){
this.modelname=modelname;
this.modelyear=modelyear;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[])  {
try{
Vehicle v = new Vehicle();
Vehicle v1=(Vehicle)v.clone();
System.out.println(v. modelname +" "+ v. modelyear);
System.out.println(v1. modelname +" "+ v1. modelyear);
}catch(CloneNotSupportedException e){
}
}
Social Share:

0 responses on "Java Clone Object"

Leave a Message

Your email address will not be published. Required fields are marked *