我发现了很多关于抽象类和接口的问题,但回答我这个:抽象类可以做接口可以做的所有事情吗?
我真的很困惑,我读了很多关于这个主题的问题,但我无法具体指出接口可以做到抽象类无法做到的任何事情。
有什么是接口可以做但抽象类不能做的事情吗?
我在我的 Java 类的上下文中询问,但如果它也适用于其他语言(可能是 C#?),请随意删除 java 标签。
编辑:我知道抽象类可以做接口不能做的事情,但是如果抽象类可以做接口可以做的所有事情,那么接口还有什么意义呢? “实现多个接口”是什么意思?
I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
Is there anything an interface can do that an abstract class cannot do?
I am asking in the context of my Java class, but feel free to remove the java tag if it applies to other languages as well (possibly C#?).
Edit: I understand that an abstract class can do things an interface cannot, but if an abstract class can do everything an interface can do, then what is the point of an interface? What does "implement multiple interfaces" mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
接口本身无法完成抽象类所做的事情。
这是因为抽象类可以包含代码,而接口则不能。但是任何给定的类只能有一个超类 -
扩展
- 而不是任意数量的接口 -实现
,所以如果你使用抽象类本质上把自己描绘在继承树的一个角落里,因为你的类只能扩展一个类。此限制不适用于接口,允许单个类具有多种用途,具体取决于它实现的接口数量。
Interfaces as such cannot do what abstract classes do.
This is because abstract classes can contain code - interfaces cannot. But any given class can only have one superclass -
extends
- as opposed to any number of interfaces -implements
, so if you use abstract classes you essentially paint yourself in a corner of the inheritance tree, because your class can only extend a single class.This limitation does not apply to interfaces, allowing a single class to have many purposes depending on how many interfaces it implements.
C# 中不能继承多个抽象类,但可以实现多个接口。
我认为这也可能适用于 java
编辑:
你不能从多个类继承。如果您有一个名为 Clonable 的抽象类和一个名为 Disposable 的抽象类,那么您只能继承这些类中的一个,并且您被迫决定您的类应该是哪个类的子类型:
例如:
注意它是一个该语言的设计决定只允许您从一个类继承。
另一方面,如果您有接口,则该语言允许您实现这两个接口,
例如
You can't inherit from multiple abstract classes in c#, but you can implement multiple interfaces.
I think this may apply to java too
Edit:
You can't inherit from multiple classes. If you have an abstract class called Clonable, and an abstract class called Disposable then you can only inherit one of these classes and you're forced to make a decision about which class your class should be a subtype of:
e.g:
Note it is a design decision of the language to allow you only to inherit from one class.
If on the other hand you have interfaces, the language allows you to implement both
e.g.
仔细阅读:
考虑:
当类实现
Ifun
时,则:Collections.sort
自动排序。这意味着对象可以有超过 1 个接口。
Well read:
Consider:
When class implements
Ifun
, then:Collections.sort
.It means object can have more then 1 interface.
接口是不可实例化的类,仅包含子类可以继承的方法。接口(在java中)唯一能做的就是一个类可以实现许多接口,而一个类只能扩展1个抽象类。
Interfaces are non instantiable classes that only contains methods that subclasses can inherit. The only thing that interfaces can do (in java) is that a class can implement many interfaces while a class can only extend 1 abstract class.