=================================在编辑之前======= =================================在抽象超类中覆盖克隆
我对Java有点新,所以请耐心等待:)
我创建了一个超类。
public abstract class Employee
我尝试做覆盖对象克隆以下
@Override
public Employee clone()
{
Employee foo;
try
{
foo = (Employee) super.clone();
}
catch (CloneNotSupportedException e)
{
throw new AssertionError(e);
}
return foo;
}
我创建了一个子类
public class Employee_Subclass extends Employee
由于只有一个构造函数。
在上面,我有我的主程序。
从主程序我试图克隆Employee_Subclass
的对象,但未成功。
是否可以在超类中克隆一个子类的对象只有克隆函数?
我不断收到我
Exception in thread "main" java.lang.AssertionError: java.lang.CloneNotSupportedException: test_project.Employee_Subclass
at test_project.Employee.clone(Employee.java:108)
at test_project.Test_Project.main(Test_Project.java:22)
Caused by: java.lang.CloneNotSupportedException: test_project.Employee_Subclass
at java.lang.Object.clone(Native Method)
at test_project.Employee.clone(Employee.java:104)
... 1 more
Java Result: 1
任何想法,我怎么能做到这一点正确抛出的AssertionError的?
谢谢。
============================================== ====================================
好吧,我添加了可克隆的,这就是我有
public abstract class Employee implements Cloneable
{
private String firstName;
private String lastName;
private String socialSecurityNumber;
private Date_Of_Birth Date_Of_Birth_Inst;
// three-argument constructor
public Employee(String first, String last, String ssn, int Day,
int Month, int Year)
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
Date_Of_Birth_Inst = new Date_Of_Birth(Day, Month, Year);
}
....
Some Get and Set functions.
....
@Override
protected Employee clone() throws CloneNotSupportedException {
Employee clone = (Employee) super.clone();
return clone;
}
}
这里是子类
public class Employee_Subclass extends Employee{
public Employee_Subclass(String first, String last, String ssn, int Day,
int Month, int Year)
{
super(first, last, ssn, Day, Month, Year);
}
}
只有构造。
这里是主文件。
public class Test_Project {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws CloneNotSupportedException {
Employee_Subclass Employee_Inst = new Employee_Subclass("Hello", "World",
"066499402", 7, 6, 1984);
Employee_Subclass Employee_Inst1;
Employee_Inst1 = (Employee_Subclass) Employee_Inst.clone();
}
}
我不得不添加throws CloneNotSupportedException
否则将无法正常工作。
所以我的问题是它是如何工作的?
当我调用Employee_Inst.clone()时,它会调用Employee中的克隆函数,对吧?
现在,这个函数返回一个Employee对象,所以我怎样才能将它插入到子类对象中呢?
至于深度克隆,我做对了吗? Date_Of_Birth_Inst呢,它复制正确吗?
非常感谢。
我没忘,我只是不知道:)谢谢 – user2102697 2013-04-05 13:38:46