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

When we know that in java, all classes extend the Object class by default, so why are there methods with an open modifier where, as protected, there will be enough access to these methods from any class? So what information is needed about this. thank.

+5
source share
4 answers

If the Object methods were not public (or areas with a package), you could not call them because of the child. The fact that they are inherited by all Java objects is orthogonal to the definition of these methods.

Quick example: how often do you call x.toString()? You could not do this if this method was not publicly available. And if this method did not exist at all in Object, you will have to reimplement it for each new class.

+11
source

clone()is a protected method for Object, and you cannot call clone()instances of other classes.

+1
source

< a > , , .

, :

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);
    }
}

:

public class Test2 {
    public static void main() {
         Test1 test1 = new Test1();
         test1.clone();   // The method clone() from the type Object is not visible
    }
}

</a >

toString(), equals(Object), hashCode() getClass() on all objects makes things a lot easier.

clone() finalize() . , , . , , .

, , Sun , "" notify(), notifyAll(), wait(long), wait (long, int). , Object , Lock-. , , , .

+1

, , Object:

The Java language specification defines the value protectedas follows:

A protected member or constructor of an object can be accessed from outside the package, in which it is declared only by the code that is responsible for the implementation of this object.

That is, a subclass of S can call protected constructors / members of superclass C only for instances of S.

+1
source

All Articles