何时实现接口以及何时扩展超类? [英] When to implement an interface and when to extend a superclass?

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

问题描述

我在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?

推荐答案

如果要定义合同,请使用界面。即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天全站免登陆