什么时候实现接口,什么时候扩展超类? [英] When to implement an interface and when to extend a superclass?

查看:39
本文介绍了什么时候实现接口,什么时候扩展超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于 Java 中的接口和类继承的文章,我知道如何做到这两点,而且我认为我对两者都有很好的感觉.但似乎没有人真正将两者并列比较并解释何时以及为什么要使用其中之一.我没有发现很多时候实现接口比扩展超类更好的系统.

I've been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever really compares the two side by side and explains when and why you would want to use one or the other. I have not found a lot of times when implementing an interface would be a better system than extending a superclass.

那么什么时候实现接口,什么时候扩展超类?

So when do you implement an interface and when do you extend a superclass?

推荐答案

如果您想定义合同,请使用接口.IE.X 必须接受 Y 并返回 Z.它不关心如何代码是这样做的.一个类可以实现多个接口.

Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.

如果您想在非抽象方法中定义默认行为,请使用抽象类,以便最终用户可以重用它而无需一次又一次地重写.一个类可以从仅一个其他类扩展.只有抽象方法的抽象类可以像接口一样被很好地定义.没有任何抽象方法的抽象类可以识别为模板方法模式(请参阅此答案以了解一些真实示例).

Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).

只要您想为最终用户提供定义默认行为的自由,抽象类就可以完美地实现接口.

An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.

这篇关于什么时候实现接口,什么时候扩展超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆