Question

Why does the Object class in Java contain protected methods, such as clone() and finalize(), if all classes you use or write inherit the instance methods of Object?

Was it helpful?

Solution

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.

These rules apply even if C1 is the Object class. So I think the reason is so that classes (which all inherit from Object) can declare their own overriding clone and finalize methods and make them protected if they choose, instead of public.

EDIT: An important consequence of this is that clone and finalize are not as freely accessible as a public member would be. Within class C2, you can use clone and finalize on an object of type C2 all you want, since they are protected methods and therefore available to the subclass C2. But you can't necessarily use them on objects of another class.

class X { }

class Y {
    private Y field1;
    private X field2;
    public void foo() throws Exception {
        Object o1 = this.clone();      // legal
        Object o2 = field1.clone();    // legal
        Object o3 = field2.clone();    // illegal
        String s1 = field2.toString(); // legal since toString() is "public" in Object
    }
}

This should demonstrate that although protected methods are accessible to subclasses, there are still some restrictions on how accessible they are. Note that if X had an @Override public Object clone() method, then the declaration of o3 would become legal.

OTHER TIPS

There are two protected methods in Object: clone() and finalize().

finalize() is not intended to be called by client code, but may be overridden by subclasses - thus, it is protected.

clone() of Object is not intended to be called by clients either - unless it has explicitly been overridden and made public by a subclass.

This is done because for generic abstract Object it is unclear what to do if user wants to clone it for example, or finalize. That's why we have a chance to override this methods and create our own implementation.

Object class contains finalise() and clone() method with protected modifier so that developer can decide whether these method can be overridden with protected or public modifier.Means it totally depends on the requirement wether we are going to allow client code to call these methods or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top