Could someone tell me why I keep getting the exception error in Clone() method?
You are Awesome! :(nod):
Code:public class Person
{
private String name;
private Date born;
private Date died;//null indicates still alive.
public Person(){
name = null;
born = new Date();
died = new Date();
}
public Person(String initialName, Date birthDate, Date deathDate)
{
if (consistent(birthDate, deathDate))
{
name = initialName;
born = new Date(birthDate);
if (deathDate == null)
died = null;
else
died = new Date(deathDate);
}
else
{
System.out.println("Inconsistent dates. Aborting.");
System.exit(0);
}
}
.
.
.
public Object Clone()
{
try
{
Person copy;
copy = (Person)super.clone();
copy.name = (String)super.clone();
copy.born = (Date)super.clone();
copy.died = (Date)super.clone();
return copy;
}catch(CloneNotSupportedException e){
System.err.print("Error on Cloning!");
e.printStackTrace();
return null;
}
}
}
Code:
public class PersonDemo
{
public static void main(String[] args)
{
Date date = new Date();
Person bach =
new Person("Johann Sebastian Bach",
new Date("March", 21, 1685), new Date("July", 28, 1750));
Person stravinsky =
new Person("Igor Stravinsky",
new Date("June", 17, 1882), new Date("April", 6, 1971));
Person adams =
new Person("John Adams",
new Date("February", 15, 1947), null);
System.out.println("A Short List of Composers:");
System.out.println(bach);
System.out.println(stravinsky);
System.out.println(adams);
Person bachTwin = (Person)bach.Clone();//cloning
System.out.println("Comparing bach and bachTwin:");
if (bachTwin == bach)
System.out.println("Same reference for both.");
else
System.out.println("Distinct copies.");
if (bachTwin.equals(bach))
System.out.println("Same data.");
else
System.out.println("Not same data.");
}
}

