简体   繁体   English

子类Java的超类方法

[英]Superclasses methods for subclasses Java

Does a subclass need to rewrite each method of the superclass or it isn't mandatory to do so but the subclass can override some methodes of the superclass. 子类是否需要重写超类的每个方法,或者不是必须这样做,但是子类可以覆盖超类的某些方法。 I am a bit confused. 我有点困惑。

Subclasses are not required to override any parent methods, even though they can. 子类不需要重写任何父方法,即使它们可以。 The only way to force a child class to override a method is to make that method abstract (and the parent class has to be abstract as well). 强制子类重写方法的唯一方法是使该方法抽象(父类也必须是抽象的)。

If a subclass wishes to introduce unique behavior for invocation of a method that it inherited, then that method must be overridden. 如果子类希望引入独特的行为来调用其继承的方法,则必须重写该方法。

The most common cases for this: toString , equals and hashCode are all eligible to be overridden for all of your custom classes, given that your custom class doesn't want to leverage Object#toString , Object#equals or Object#hashCode , which are all "unhelpful" for your custom implementations. 鉴于您的自定义类不想利用Object#toStringObject#equalsObject#hashCode ,这是最常见的情况: toStringequalshashCode都可以被所有自定义类覆盖对于您的自定义实现,所有“无用”。

If a subclass does not wish to introduce unique behavior for invocation of a method that it inherited, then this is unnecessary. 如果子类希望引入独特的行为为它继承方法的调用,那么这是不必要的。 You can rely on the parent class' behavior instead. 您可以改为依赖父类的行为。

If your parent class is abstract , then you have no choice but to implement what methods the parent class chose not to implement. 如果您的父类是abstract ,那么您别无选择 ,只能实现父类选择不实现的方法。

If you're implementing an interface, the same principle as abstract classes applies - because the interface does not implement anything itself, you must implement the methods that the interface prescribes. 如果要实现接口,则应采用与抽象类相同的原理-由于该接口本身未实现任何东西,因此必须实现该接口规定的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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