我们何时应该使用Java中的接口或抽象类? [英] When shall we go for interface or abstract class in Java?

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

问题描述


可能重复:

何时使用接口而不是抽象类,反之亦然?

任何人都可以告诉我在什么情况下应该选择接口和抽象类。

Can any one tell me under which circumstances we should go for interface and abstract class.

欢迎Java特定方面。

Java specific aspects are welcome.

推荐答案

除非您需要,否则始终使用界面...

Always use an interface unless you need to ...


  • ...为子类提供一些 state

  • ...提供某些方法的默认实现

  • ...想要推迟某些抽象方法的实现

  • ... provide subclasses with some state
  • ... provide subclasses with default implementations of some methods
  • ... want to defer implementation of some of the abstract methods

请注意,您只能扩展一个类,同时可以实现多个接口。因此,如果子类有可能需要扩展其他类,请努力使用接口。

Note that you can only extend one class, while you can implement multiple interfaces. So if there's any chance that a subclass will need to extend some other class, strive for using an interface.

以下是一些讨论此主题的好链接:

Here are some good links that discusses this topic:

  • Java World: Abstract classes vs. interfaces
  • Interface vs Abstract Class (general OO)
  • Abstract Class versus Interface
  • Mindprod: Interfaces vs Abstract classes

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

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