2017-10-28 23 views
-3
class Parent implements Cloneable{ 

    int i ; 

    Parent(){ 

    } 
    Parent(int i){ 
     this.i = i; 
    } 

    public Object clonemyobj() throws CloneNotSupportedException{ 
     return this.clone(); 
    } 

    protected Object cloneme() throws CloneNotSupportedException { 
     return this.clone(); 
    } 

} 

class Child extends Parent{ 

} 

public class CloneDemo{ 
    public static void main(String... ar) throws CloneNotSupportedException 
    { 
     Parent p = new Parent(10); 

     Object o1 = p.cloneme(); 
     // 1. cloneme() is a protected method in parent class i am able to access it 

     //Object o2 = p.clone(); 
     // 2. the above line shows clone() has protected access in java.lang.object 
     // but that should be the same with cloneme() method in parent class 
     // why? 
     Object o = new Object(); 

     Child c = new Child(); 
     //3. o.clone(); 
     c.cloneme(); 
     //4.(c.cloneme()) is a protected method in parent class 
     // but still able to access it using child class object 
    } 
} 

위의 모든 클래스는 동일한 패키지에 있습니다.보호 액세스 수정자는 작동하며 Object 클래스 복제 방법에 액세스하는 것과 어떻게 다른가요

  1. 위의 네 가지 글 머리 기호 모두에 대해 설명해 줄 수있는 사람이 있습니까?
  2. 이들 각각은 어떻게 실행됩니까?
+1

[편집] 질문에 올바른 코드와 텍스트 서식을 지정하십시오. – user1803551

+0

코드와 텍스트 포맷을 수정했습니다 –

+0

왜이 코드를 실행하고 * 각각의 실행 방법은 무엇입니까? * – NewUser

답변

0

protected 방법은 같은 클래스 내에서 액세스 할 수 있으며 동일한 패키지 내에서 에스 클래스에게뿐만 아니라, 을 하위 클래스. 클래스가 java.lang 패키지에 없으므로 clone 메소드 java.lang.Object에 액세스 할 수 있습니다. 소유 한 클래스 및 해당 하위 클래스의 오브젝트에 대해서만 가능합니다. ParentCloneDemo는 동일한 패키지에 상주하기 때문에 대조적으로

Parent에 선언 자신의 protected 방법은 CloneDemo에서 액세스 할 수 있습니다.

그러나 당신이 Parent

protected Object clone() throws CloneNotSupportedException { 
    return super.clone(); 
} 

, 당신은 의미를 변경하지 않는 재정clone() 방법, 즉 추가 할 경우주의,하지만 Parent.clone()는 동일한에 상주하는 CloneDemo에서 지금 액세스 패키지는 Parent입니다. 따라서 CloneDemoParentChild의 인스턴스에서 clone()을 호출 할 수 있습니다.