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

All my above classes are in same package.

  1. can anyone provide me with explanation for all the above four bullet points?
  2. How would each of these would execute?
user1803551
  • 12,965
  • 5
  • 47
  • 74
ALLEN
  • 1
  • 2
  • 1
    [Edit] your question to have proper code and text formatting. – user1803551 Oct 28 '17 at 11:47
  • fixed your code and text formatting – Thomas Fritsch Oct 28 '17 at 12:41
  • Why don't you run it and see *how would each of these execute?* – NewUser Oct 28 '17 at 12:44
  • @NewUser just i have added in comments what i observed after running , but i am not clear , why i am unable to call clone method on parent class from main method in cloneDemo class , but at the same time i am able to call other protected methods of parent class – ALLEN Oct 28 '17 at 16:59

1 Answers1

0

protected methods can be accessed within the same class and it subclasses, as well es classes within the same package. Since your classes are not in the java.lang package, you can access the clone method of java.lang.Object only for objects of you own classes and its subclasses.

In contrast, your own protected method declared in Parent are accessible from CloneDemo, because Parent and CloneDemo reside in the same package.

But note that you can override the clone() method, i.e. if you add

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

to Parent, you are not changing the semantics, but Parent.clone() is now accessible from CloneDemo, which resides in the same package as Parent. Therefore, CloneDemo can now invoke clone() on instances of Parent and also of Child.

Holger
  • 285,553
  • 42
  • 434
  • 765