views:

67

answers:

3

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.

+1  A: 

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".

Bozho
@Bozho: As I commented , I am not overriding clone method.But why I am not able to access that method from Class B?
JavaUser
@JavaUser - you definitely are overriding it in `A`!
Bozho
@Bozho : No I am not overriding .I said the implicit meaning of inheriting from Object.
JavaUser
then remove the snippet where you show how you override it ;) and check my update - the first sentence
Bozho
Anyway , I am only accessing the clone() method of my class A not Object.I didn't say Object obj.clone() ..I said A a.clone() ??!!!
JavaUser
it's not how it works - check my update
Bozho
+1  A: 

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

}
Xavier Combelle
@Xavier : As I commented out I am not overriding clone method.Please remove the clone method from the above snippet and compile the code.
JavaUser
@JavaUser: that was not clear in your question so you have not a protected clone() in your A object it stays as a Object protected method and as such can't be called outside of the java.lang package
Xavier Combelle
A: 

If you don't redefine the clone method for A, then, don't be surprise if you are indeed invoking Object's clone() method and not A's.

You get the very same error with

class A {}

class B {
  A a = new A();

  public B() {
    A x = (A) ((Object) a).clone();
  }
}
dodecaplex