When we know that in java all classes by default extends Object class, so why there are methods with public modifier where as protected would suffice the accessing of these methods from any class? So need some info on this. thanks.
-
5Why would they not be public? `where as protected would suffice the accessing of these methods from any class` - I don't think protected means what you think it does. – Amy B Aug 15 '10 at 15:29
4 Answers
If Object methods weren't public (or package-scoped), you couldn't call them from outside the child object. The fact that they are inherited by all Java objects is orthogonal to the scoping of these methods.
Quick example: how often do you call x.toString()
? You couldn't do that if that method weren't public. And if that method didn't exist in Object at all, you'd have to re-implement it for every new class.

- 7,003
- 5
- 36
- 54
clone()
is a protected method on Object and you can't call clone()
on instances of other classes.

- 113,398
- 19
- 180
- 268
<Edit> Although one object can access private properties of all objects of the same class, you cannot access protected methods of an object from other class even if the protected method is defined in a common super class.
So while this code compiles:
public class Test {
private int x;
private void change(Test test) {
test.x = test.x + 1;
}
public static void main() {
Test test1 = new Test();
Test test2 = new Test();
test1.change(test2);
}
}
The following code will not compile:
public class Test2 {
public static void main() {
Test1 test1 = new Test1();
test1.clone(); // The method clone() from the type Object is not visible
}
}
</Edit>
Being able to call toString()
, equals(Object)
, hashCode()
and getClass() on all objects makes things a lot easier.
clone()
and finalize()
are protected. So in order to be able to call them from the outside the subclass has to increase the visibility. And that is obviously a design decision.
To be honest, i have no idea why Sun decided that all object are "locks" and have notify()
, notifyAll()
, wait(long)
, wait(long, int). From my point of view those method should not be in Object at all but in a specialized Lock-class. But I guess there was a good reason to have them there in the very early days and it cannot be changed nowadays without breaking compatibility.

- 8,242
- 3
- 31
- 55
as protected would suffice the accessing of these methods from any class
From any class, yes, but not on any Object
:
The Java Language Spec defines the meaning of protected
as follows:
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
That is, a subclass S may invoke protected constructors/members of a super class C only on instances of S.

- 68,356
- 14
- 108
- 175