==================================编辑前=============== ==========================
我对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
,但未成功。
是否可以在超类中仅使用克隆功能克隆子类的对象?
我不断收到向我抛出的 AssertionError
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
知道如何正确地做到这一点吗?
谢谢。
==================================================== =================================
好的,所以我添加了可克隆,这就是我所拥有的
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 中的 clone 函数,对吗?
现在,这个函数返回一个Employee对象,那么我怎样才能将它插入到子类对象中呢?
至于深层克隆,我做对了吗?Date_Of_Birth_Inst 怎么样,是否正确复制?
非常感谢。