2012-09-22 43 views
6

背后代码:的java:克隆方法违反

class A implements Cloneable 
{ 
    int i, j; 

    A(int i, int j) 
    { 
     this.i = i; 
     this.j = j; 
    } 

    A() 
    { 
    } 
} 

class B extends A 
{ 
    int l, m; 

    B() 
    { 
    } 

    B(int l, int m) 
    { 
     this.l = l; 
     this.m = m; 

    } 

    public static void main(String l[]) 
    { 
     A obj = new A(1, 2); 
     B obj1 = (B) obj.clone(); // ERROR 
    } 
} 

我知道我违反克隆的意思,因为我想一个对象的字段分配到一个完全不同的对象。但它的错误陈述令我困惑。

声明:“错误:克隆()已在受保护对象访问”

延伸的应该clone()提供给B还?如果是这样,那么i和j的值应该被复制到l和m中?这可能吗 ?

回答

7

clone()是受保护的方法,并使其在子类中可访问,用public访问覆盖它。

class A implements Cloneable{ 
    ..... 
    @Override 
    public Object clone() throws CloneNotSupportedException{ 
     return super.clone(); 
    } 
} 
+0

如果clone()受保护,那么它对A可用,如果B扩展A,那么B应该有权访问克隆? – Nil

+0

@ rd4code查看我的回答。 B有权访问克隆方法。但是B应该通过继承来访问它,而不是直接通过A来访问它。 – CKing

3

Cloneable

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

Clone的Javadoc是在Java中,早期的设计之一,它有缺陷

关于访问 - When a method is protected, it can only be accessed by the class itself, subclasses of the class, or classes in the same package as the class

因此,它是在AB类你正在做的方式访问是唯一可能的,如果你在出现这种情况是java.lang

可以提供内部A这样一些方法相同的包。

public A copy() throws CloneNotSupportedException { 
     return (A) clone(); 
    } 

正确执行

@Override 
    public Object clone() throws CloneNotSupportedException { 
     return super.clone(); 
    }; 

还记得父母是不是孩子从A到B将无法工作,所以铸造的类型。孩子是父母的类型,所以从B到A的投射将起作用。