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.
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 .
There are five of these methods: public final void notify() public final void notifyAll() public final void wait()
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.
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.
clone()
is a protected method on Object and you can't call clone()
on instances of other classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With