开发者

accessing protected method in other package?

If 开发者_开发技巧I say

class A{
}

then it implicitly inherits Object class.So I am having the class as below:

class A{

       protected Object clone(){
       }  /// Here i am not overridning
       //All the other methods (toString/wait/notify/notifyAll/getClass)
}

Now Why cant I access the clone() method in Class B which is in the same package of class A.

Class B{
       A a = new A();
       a.clone();
       **
}

//** Says clone is protected in Object class . But I am not accessing Object's clone method .Here I am invoking class A's clone method anyway which I havn't overloaded yet.


The protected method is defined in the java.lang.Object, so you can't invoke it from another package - only from subclasses.

You are calling it on a a reference to A but it is a method of java.lang.Object, until you override it.

When overriding clone(), you should change the modifier to public and implement Cloneable. However using the clone() method is not a good idea, because it's very hard to implement it correctly. Use commons-beanutils to make shallow clones.

Make sure you make distinction between "overriding" and "overloading".


this perfectly work

class A{

       protected Object clone(){
           return this;
       }  
}

public class B{
       public B() {
           A a = new A();
           a.clone();
           System.out.println("success");
       }
       public static void main(String[] args) {
        new B();
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜