何时使用抽象类或接口? [英] When to use abstract class or interface?

查看:82
本文介绍了何时使用抽象类或接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要创建抽象类或接口类,或者何时应该使用抽象类或接口类?

Why are abstract or interface classes created, or when should we use abstract or interface classes?

推荐答案

当使用接口时你只想声明一个类必须有哪些方法和成员。任何实现接口的人都必须声明并实现接口列出的方法。

Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.

如果您还想要一个默认实现,请使用抽象类。扩展抽象类的任何类都必须只实现其抽象方法和成员,并且将具有抽象类的其他方法的一些默认实现,您可以覆盖或不重写。

If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.

- 编辑 - 忘了提及,Earwicker提醒我

--EDIT - forgot to mention, Earwicker reminded me

最后,你可以实现任意数量的接口,但只能扩展一个类(就是它)抽象与否)。在选择之前请记住这一点。

Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.

这篇关于何时使用抽象类或接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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