If class C2
extends C1
, and C1
contains a public
method, then the method in C2
(if overridden) must also be public
; Java makes it illegal to put additional restrictions on a method's access when overriding. If C1
contains a protected
method, then an overriding method in C2
may be protected
or public
.
These rules apply even if C1
is the Object
class.
So I think the reason is so that classes (which all inherit from Object
) can declare their own overriding clone
and finalize
methods and make them protected
if they choose, instead of public
.
EDIT: An important consequence of this is that clone
and finalize
are not as freely accessible as a public member would be. Within class C2
, you can use clone
and finalize
on an object of type C2
all you want, since they are protected methods and therefore available to the subclass C2
. But you can't necessarily use them on objects of another class.
class X { }
class Y {
private Y field1;
private X field2;
public void foo() throws Exception {
Object o1 = this.clone(); // legal
Object o2 = field1.clone(); // legal
Object o3 = field2.clone(); // illegal
String s1 = field2.toString(); // legal since toString() is "public" in Object
}
}
This should demonstrate that although protected
methods are accessible to subclasses, there are still some restrictions on how accessible they are. Note that if X
had an @Override public Object clone()
method, then the declaration of o3
would become legal.