简体   繁体   中英

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

我了解将clone和finalize方法设为受保护的目的,我想了解为什么hashcode()和equals方法未声明为受保护的原因

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM