an example of a custom class that implements Cloneable
Java Interview Questions for Cloning and Cloneable
(Continued from previous question...)
an example of a custom class that implements Cloneable
The following is an example of a custom class that implements Cloneable
import java.util.Date;
public class Person implements Cloneable, Comparable<Person>{
private double height;
private int age;
private Date dateOfBirth;
public Person(double height, int age)
{
this.height = height;
this.age = age;
this.dateOfBirth = new Date();
}
public double getHeight()
{
return this.height;
}
public int getAge()
{
return this.age;
}
public Date getDob()
{
return this.dateOfBirth;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
@Override
public int compareTo(Person o) {
if (this.age > o.age)
{
return 1;
}else if (this.age < o.age)
{
return -1;
}else
{
return 0;
}
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Person))
return false;
Person otherPerson = (Person)o;
if (otherPerson.dateOfBirth.equals(this.dateOfBirth) &&
otherPerson.age == this.age && otherPerson.height == this.height)
return true;
else
return false;
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(1.8, 30);
Person person2 = (Person)person1.clone();
System.out.println("Comparing : "+person1.compareTo(person2));
System.out.println("Are they equal? : "+ (person1.equals(person2)));
System.out.println("Are they same reference? : "+ (person1 == person2));
System.out.println("Do they use the same reference for Object fields (shallow copy) :"
+(person1.getDob() == person2.getDob()));
}
}
The following is the output
Comparing : 0
Are they equal? : true
Are they same reference? : false
Do they use the same reference for Object fields (shallow copy) :true
(Continued on next question...)
Other Interview Questions
|