Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there are public methods in the Object class in java?

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.

like image 704
GuruKulki Avatar asked Aug 15 '10 15:08

GuruKulki


People also ask

Why are methods public in Java?

public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final .

How many public methods are in the Object class?

There are five of these methods: public final void notify() public final void notifyAll() public final void wait()

What are public methods in Java?

Public methods are methods that are accessible both inside and outside the scope of your class. Any instance of that class will have access to public methods and can invoke them.


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

like image 76
G__ Avatar answered Nov 15 '22 11:11

G__


clone() is a protected method on Object and you can't call clone() on instances of other classes.

like image 43
Andreas Dolk Avatar answered Nov 15 '22 11:11

Andreas Dolk