覆盖抽象超类中的克隆

时间:2013-04-05 09:48:54

标签: java override clone

=================================编辑之前============ ============================

我对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

我知道如何正确地做到这一点?

感谢。

=============================================== ===================================

好的,所以我添加了clonable,这就是我所拥有的

    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,它被正确复制了吗?

非常感谢。

4 个答案:

答案 0 :(得分:2)

您只是忘了让您的Employee类实现Cloneable。

答案 1 :(得分:0)

您需要implement Cloneable班级中的Employee

答案 2 :(得分:0)

我建议你实现一个拷贝构造函数,而不是使用Cloneable接口。有关详细信息,请参阅Joshua J. Bloch explanation

答案 3 :(得分:0)

您需要实现Cloneable接口。以下示例可能有助于您理解深度克隆和浅层克隆。

import java.util.ArrayList;
import java.util.List;

public class DeepCopy implements Cloneable {
    private List<String> hobbiesList;
    private int age;
    private String name;
    private float salary;

    public static void main(String[] args) throws CloneNotSupportedException {
        DeepCopy original = new DeepCopy();
        original.name = "AAA";
        original.age = 20;
        original.salary = 10000;
        original.hobbiesList = new ArrayList<String>();
        original.hobbiesList.add("Cricket");
        original.hobbiesList.add("Movies");
        original.hobbiesList.add("Guitar");
        original.hobbiesList.add("Eating");

        DeepCopy cloned = (DeepCopy) original.clone();
        System.out.println("original:=" + original);
        System.out.println("cloned  :=" + cloned);
        System.out.println("After adding two more hobbies in 'original' which untimately reflected in 'cloned'");
        cloned.name = "BBB";
        cloned.age = 27;
        cloned.salary = 18237;
        cloned.hobbiesList.add("Trecking");
        System.out.println("original       :=" + original);
        System.out.println("cloned  changed:=" + cloned);
    }

    @Override
    protected DeepCopy clone() throws CloneNotSupportedException {
        DeepCopy clone = (DeepCopy) super.clone();
        clone.hobbiesList = new ArrayList<String>(clone.hobbiesList);
        return clone;
    }

    @Override
    public String toString() {
        return "My name is (String)" + name + " having age (int)" + age + ". I earned (float)" + salary + " and hobbies are (ArrayList)" + hobbiesList;
    }
}