Answer Posted / radhika
Java uses clone() of Object class to copy content of 1
object to other object. Classes can implement Cloneable
Interface to override clone() method of object class.
The following sample code will show the procedure for
implementing cloneable interface.
public class CloneExp implements Cloneable {
private String name;
private String address;
private int age;
private Department depart;
public CloneExp(){
}
public CloneExp(String aName, int aAge, Department aDepart) {
this.name = aName;
this.age = aAge;
this.depart = aDepart;
}
protected Object clone() throws CloneNotSupportedException {
CloneExp clone=(CloneExp)super.clone();
// make the shallow copy of the object of type Department
clone.depart=(Department)depart.clone();
return clone;
}
public static void main(String[] args) {
CloneExp ce=new CloneExp();
try {
// make deep copy of the object of type CloneExp
CloneExp cloned=(CloneExp)ce.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
| Is This Answer Correct ? | 3 Yes | 3 No |
Post New Answer View All Answers
Is Java a dying language?
What is final method?
How to perform bubble sort in java?
Why to use nested classes in java?
Can java arraylist hold different types?
How do you find the absolute value?
What is a data structure java?
What does the “static” keyword mean? Can you override private or static method in java?
How do you convert boolean to boolean?
Define an applet in java?
What is an infinite loop? How infinite loop is declared?
What is java volatile?
Which keyword specify that a variable is effectively final ?
What is the syntax and characteristics of a lambda expression?
Explain the difference between abstract classes and interfaces in java?