11:07 am - Tuesday October 24, 2017

Java Program used to create copy of an object using clone() method.

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

The java.lang.Object.clone() creates and returns a copy of this object

Example Program

import java.util.GregorianCalendar;

public class Clone {
	public static void main(String[] args) throws CloneNotSupportedException {
		// create a gregorian calendar, which is an object
		GregorianCalendar cal = new GregorianCalendar();

		// clone object cal into object x
		GregorianCalendar x = (GregorianCalendar) cal.clone();

		// print both cal and x
		System.out.println("" + cal.getTime());
		System.out.println("" + x.getTime());

	}

}

Output

Mon Sep 22 11:54:14 IST 2014

Mon Sep 22 11:54:14 IST 2014

Description

The java.lang.Object.clone() creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x

will be true, and that the expression:

x.clone().getClass() == x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that:

x.clone().equals(x)

will be true, this is not an absolute requirement.

Declaration

Following is the declaration for java.lang.Object.clone() method

protected Object clone()

Parameters

  • NA

Return Value

This method returns a clone of this instance.

Exception

  • CloneNotSupportedException — if the object’s class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

BACK

 

 

Filed in: Z-A All Java Codes

Comments are closed.