Vignesh
Vignesh

Reputation: 101

why only clone and finalize are protected method in object calss?

I understand the purpose of making the clone and finalize method as protected, I wanted to understand why hashcode() and equals method are not declared as protected

Upvotes: 2

Views: 386

Answers (2)

LuCio
LuCio

Reputation: 5193

You "understand the purpose of making the clone and finalize method as protected". But what is the purpose actually?

Calling Object.clone will throw an exception if the method isn't overridden and if Cloneable isn't implemented. Thus this method isn't ready to use.

Object.finalize is according to JavaDoc "called by the garbage collector". Thus it is for internal usage only.

In contrast to these both methods are Object.equals and Object.hashCode ready to use and not for internal usage.

The JavaDoc of Object.hashCode says:

This method is supported for the benefit of hash tables such as those provided by HashMap.

Thus it is intended to be used by other objects. If hashCode wouldn't be declared public this functionality would be limited usable.

Object.equals is a symmetric method. If Object.equals wouldn't be declared public, suppose we have a local variable b of a type from another package and whose equals method isn't visible to this. We want to ckeck if b and this are equal. We couldn't call b != null && b.equals(this) but we could still call this.equals(b). Does it makes sense to limit a symmetric method to be callable by one of both objects only?
See also Comparable.

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32535

Because you want to call hashcode and equals methods from the outside of that given class.

protected allows access only from the same package and extending classes.

Upvotes: 6

Related Questions