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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
This is done because for generic abstract
Object
it is unclear what to do if user wants toclone
it for example, orfinalize
. That's why we have a chance to override this methods and create our own implementation.If class
C2
extendsC1
, andC1
contains apublic
method, then the method inC2
(if overridden) must also bepublic
; Java makes it illegal to put additional restrictions on a method's access when overriding. IfC1
contains aprotected
method, then an overriding method inC2
may beprotected
orpublic
.These rules apply even if
C1
is theObject
class. So I think the reason is so that classes (which all inherit fromObject
) can declare their own overridingclone
andfinalize
methods and make themprotected
if they choose, instead ofpublic
.EDIT: An important consequence of this is that
clone
andfinalize
are not as freely accessible as a public member would be. Within classC2
, you can useclone
andfinalize
on an object of typeC2
all you want, since they are protected methods and therefore available to the subclassC2
. But you can't necessarily use them on objects of another class.This should demonstrate that although
protected
methods are accessible to subclasses, there are still some restrictions on how accessible they are. Note that ifX
had an@Override public Object clone()
method, then the declaration ofo3
would become legal.There are two
protected
methods inObject
:clone()
andfinalize()
.finalize()
is not intended to be called by client code, but may be overridden by subclasses - thus, it is protected.clone()
ofObject
is not intended to be called by clients either - unless it has explicitly been overridden and madepublic
by a subclass.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.