clone只能通过super来调用吧?而且你也必须要复写clone方法啊?

解决方案 »

  1.   

    一般情况下,需要重载Point1的clone()方法。
      

  2.   

    http://java.sun.com/docs/books/tutorial/java/javaOO/objectclass.html
      

  3.   

    The simplest way to make your class cloneable then, is to add implements Cloneable to your class's declaration. For some classes the default behavior of Object's clone method works just fine. Other classes need to override clone to get correct behavior. 先 class Point1 implements Cloneable 
    如果不理想
    再protected Object clone() {
      ...
    }
      

  4.   

    编译时出现下面两个错误:
    A.java:20: clone() has protected access in java.lang.Object
                    Point1 p1 = p.clone();//
                                 ^
    A.java:20: incompatible types
    found   : java.lang.Object
    required: Point1
                    Point1 p1 = p.clone();//第一个错误的原因是:在Object中,clone()方法是protected的,不是public的,只能在类的内部调用,不能在外部调用;第二个错误的原因是:clone()方法的返回值类型是Object,但是在上面的代码中,却直接赋给了Point1类型的p1变量;类型部匹配肯定会出错。在JAVA中要实现clone功能,需要做两件事情:
    1.implements Cloneable借口;
    2.覆盖Object中的clone()方法;如果你需要在类的外部调用这个方法,需要将这个方法修饰为public.
    下面是改进后的代码:class Point1 implements Cloneable
    {
    int x,y;
    Point1(){
    x = 10;
    y = 20;
    }
    Point1(int x1,int y1){
    x = x1;
    y = y1;
    }
    void print(){
    System.out.println("x = "+x+"y = "+y);
    }

    public Object clone() throws CloneNotSupportedException
    {
    Point1 p = (Point1)super.clone();
    p.x = x;
    p.y = y;
    return p;
    }
    };
    public class A
    {
    public static void main(String args[]) throws Exception
    {
    Point1 p = new Point1();
    Point1 p1 = (Point1)p.clone();//在这里要做类型转化
    p.print();
    p1.print();
    }
    };