2012-09-22 7 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 
    } 
} 

私は、私は完全に別のオブジェクトに1つのオブジェクトのフィールドを割り当てるしようとしていますように私はクローンの意味を違反していますことを知っています。しかし、それは私を混乱させるエラーステートメントです。

声明:「エラー:クローン()オブジェクト内のアクセス保護されています」また、Bが利用できるclone()をしなければならない拡張

を?それで、iとjの値をlとmにもコピーする必要がありますか?これは可能ですか?

答えて

7

clone()は保護された方法であり、サブクラスでアクセスできるようにするには、publicアクセス権で上書きします。 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のから

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

は、Javaの初期のデザインの一つであり、それが欠陥

access- 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について

を持っています。

だから、あなたはあなたがA内でこのようないくつかの方法を提供することができますjava.lang

であることを起こる同じパッケージ内にある場合ABクラスであなたがそれをやっている方法はのみ可能ですアクセス可能です。

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

正しい実装

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

また親がそうBに動作しませんからキャスト子のタイプではありません覚えておいてください。子は親の型ですので、BからAへのキャストは機能します。

関連する問題