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
protectedmethod is defined in thejava.lang.Object, so you can’t invoke it from another package – only from subclasses.You are calling it on a a reference to
Abut it is a method ofjava.lang.Object, until you override it.When overriding
clone(), you should change the modifier topublicand implementCloneable. However using theclone()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”.