2012-09-22 52 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的投射將起作用。