2017-10-28 103 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 
    } 
} 

我所有的上述类都在同一个包中。受保护访问修饰符如何工作,它与访问对象类有何区别克隆方法

  1. 任何人都可以提供我解释所有上述四个要点吗?
  2. 这些都将如何执行?
+1

[编辑]你的问题有适当的代码和文本格式。 – user1803551

+0

修复了您的代码和文本格式 –

+0

为什么不运行它并查看*这些每个都会如何执行?* – NewUser

回答

0

protected方法可以在同一类内访问和它的子类,以及类ES 同一封装内。由于您的课程不在java.lang包中,因此只能为您自己的类及其子类的对象访问clone方法java.lang.Object

相反,在Parent宣布自己protected方法是从CloneDemo访问,因为ParentCloneDemo驻留在同一个包。

但请注意,您可以覆盖clone()方法,即如果添加

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

Parent,你是不是改变了语义,但Parent.clone()现在访问从CloneDemo,它驻留在同一包装为Parent。因此,CloneDemo现在可以在Parent以及Child的实例上调用clone()