Hi ranchers,
Sarada didn't understand
the reason. can anyone brief me with the explanation for the error?
... not really
brief, but:
The protected modifier means, that the member (variable or method) can be accessed everywhere inside the package.
Furthermore it can access protected members of subclasses outside the package - but only through inheritance, not directly through an instance of the superclass!
CloneTest has access to the protected method of Circle because both classes are in the same package.
But CloneTest cannot access the clone() method of class Object through an instance of Object, because Object is in a different package (Object is in java.lang, Circle and CloneTest are in the "default package").
If you say
Object ob = new Circle(6);
Object ob1 = ob.clone(); you are trying to access the method of Object, because ob's reference type is Object, it doesn't matter that its compile type is Circle here.
From a package outside of the pack where class Object is in, you can access protected members only through types that are subclasses of Object, not through class Object itself.
CloneTest
could access a protected method of class Object through an instance of itself, for example.
But in the case of clone() there would also be a second problem: it would throw a CloneNotSupportedException, but that's outside of the question.
Yours,
Bu.