HUSNAIN SARWAR
HUSNAIN SARWAR

Reputation: 95

Why The methods in Object Class Are Protected?

Why the Methods In class Object Are Protected And why its not public is there any valid reason?

protected native Object clone() throws CloneNotSupportedException;

Upvotes: 0

Views: 290

Answers (2)

Stephen C
Stephen C

Reputation: 718758

This allows the designer of a class to decide whether or not is is appropriate for the class to support cloning. The protected Object.clone() method is what a class calls to implement cloning ... if it wants to the native cloning mechanism.

If I want my class to be cloneable, I add a public clone method; e.g.

public class MyClass implements Cloneable {
    ....
    public Object clone() {
        super.clone();
    }
}

If I want cloning to be available internally, I write:

public class MyClass implements Cloneable {
    ....
    // Don't provide a public override for `clone()`.
}

If I want no cloning, I write:

public class MyClass {
    ...
}

By contrast, if Object.clone() was public, then every object would notionally support cloning ... as far as the compiler is concerned! That would be a bad thing, because there are a lot of classes where cloning makes no sense, is harmful, or cannot be implemented.


In the case of finalize(), it would be harmful if arbitrary code could initiate the finalization logic on an object. It only makes sense for the GC to do this, or in some cases for the class and its subclasses to do this.

Note that if you do implement a finalize() method it is advisable to chain to the superclass finalize(); e.g.

  protected void finalize() {
      // Do my finalization
      super.finalize();
  }

... even if the superclass currently have a finalizer.

Upvotes: 0

user4571931
user4571931

Reputation:

If class C2 extends C1, and C1 contains a public method, then the method in C2 (if overridden) must also be public; Java makes it illegal to put additional restrictions on a method's access when overriding. If C1 contains a protected method, then an overriding method in C2 may be protected or public.

Here is the stackoverflow accepted answer for more details

Why does the Object class in Java contain protected methods?

Upvotes: 1

Related Questions