TheCurious
TheCurious

Reputation: 613

Why public methods are there in object class? They can be protected and will keep same behaviour with more private manner

As for java architecture is concern "to keep things as much private as possible".Thats why finalize method is protected in object class.

protected void finalize() throws Throwable { }

Why is the finalize() method in java.lang.Object “protected”?please have a look on Mehrdad Afshari answer.

then why many other method like equals(),toString(),wait(),notify() are there public.they can be protected and they still retain their existing behaviour.where protected cause issues?``

Upvotes: 0

Views: 323

Answers (3)

Radiodef
Radiodef

Reputation: 37845

Try calling finalize:

new Object().finalize();

It won't compile: subclasses only have access to protected methods on other objects of the same type.

If equals, toString, wait and notify were protected, we could not access them freely.

In JLS terms...

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

In addition, if Id denotes an instance field or instance method, then:

  • If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E::Id, where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.

In simpler terms, protected members are accessible on...

  • ...itself:

    package ex1;
    public class Example1 {
        protected void m() {}
    }
    
    package ex2;
    import ex1.Example1;
    public class Example2 extends Example1 {{
        m(); // m is accessible
    }}
    
  • ...other instances of the same type (or a subclass of it):

    package ex3;
    import ex1.Example1;
    public class Example3 extends Example1 {{
        new Example3().m(); // m is accessible
        new Example1().m(); // m is NOT accessible
    }}
    

Upvotes: 3

Eran
Eran

Reputation: 393781

These methods have to be called by classes that have no relation to the classes for which they are called.

For example, HashMap<SomeClass> won't work if it can't call equals() and hashCode() of SomeClass, so they must be public.

Upvotes: 2

Smutje
Smutje

Reputation: 18123

finalize is not intended to be called from outside, because it shall contain code to clean up an object whilst equals(), toString(), wait(), notify() are intended to be called from another object to ensure equality, a string representation or other functionality.

Upvotes: 2

Related Questions