Java 接口和抽象类有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4126938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between an interface and an abstract class?
提问by jmasterx
Possible Duplicate:
Interface vs Abstract Class (general OO)
可能的重复:
接口与抽象类(一般面向对象)
I'm not exactly clear on the difference.
我不是很清楚其中的区别。
Thanks
谢谢
采纳答案by Mark Byers
They are quite similar but there are some important technical differences:
它们非常相似,但存在一些重要的技术差异:
- An abstract class allows you to provide a default implementation for some of the methods but an interface does not allow you to provide any implementations.
- You can implement multiple interfaces but you can only inherit from one abstract class.
- 抽象类允许您为某些方法提供默认实现,但接口不允许您提供任何实现。
- 您可以实现多个接口,但只能从一个抽象类继承。
These differences affect how the two techniques should be used:
这些差异会影响应如何使用这两种技术:
- You should use an interface to define a contract.
- An abstract class can be useful to reuse code... but be aware that it is not the only way to reuse code. You should also consider other approaches such as containment.
- 您应该使用接口来定义合同。
- 抽象类可用于重用代码……但请注意,它不是重用代码的唯一方法。您还应该考虑其他方法,例如遏制。
回答by Reese Moore
An interface doesn't allow definition of any of the member methods, whereas an abstract class does allow some or all to be defined. A class however can only extend one class (abstract or not) but can implement as many interfaces as it wants.
接口不允许定义任何成员方法,而抽象类允许定义部分或全部。然而,一个类只能扩展一个类(抽象或非抽象),但可以实现任意数量的接口。
回答by shsteimer
I like to think of an interface as a contract. any class that implements an interface, must provide details on what to do when any method defined in the contract is called. An abstract class is a class that defined a set of actual behaviors, ie more than just a contract to be implemented later, but that class can't be instantiated.
我喜欢将接口视为合同。任何实现接口的类都必须提供有关调用契约中定义的任何方法时要执行的操作的详细信息。抽象类是定义了一组实际行为的类,即不仅仅是稍后要实现的契约,而且该类不能被实例化。