2012-09-22 3 views
6

코드 :자바 : 뒤에 복제 방법 위반

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 
    } 
} 

나는 완전히 다른 개체를 하나의 개체의 필드를 지정하려고 나는이 클론의 의미를 위반하고 있음을 알고있다. 그러나 저를 혼동시키는 오류 진술.

진술 : "오류 : 클론() 객체에 액세스 보호하고있다"또한 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의 자바 독에서

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

자바의 초기 디자인 중 하나이며 결함

액세스 - 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(); 
    }; 

는 또한 부모를 기억 때문에 B에 대한 작동하지 않습니다에서 주조 아이의 유형이 아닙니다. 하위는 부모 유형이므로 B에서 A로 캐스팅하면됩니다.