=================================在編輯之前======= =================================在抽象超類中覆蓋克隆
我對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