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

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

问题描述

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

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.

--EDIT - 忘记提了,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天全站免登陆