抽象类与接口 [英] Abstract Class vs. Interface
问题描述
我已经在 SO 以及网络的其他部分搜索了一个很好的答案,但我还没有找到我真正理解的答案.我将以不同的方式呈现这个,希望答案也能帮助其他人.
I have searched around SO as well as the rest of the web for a good answer but I have't found one that I really understand. I am going to present this in a different way and hopefully the answers will help others as well.
据我了解,这两个概念有相同的规则,只是抽象类由于方法实现能力更灵活.另外,我知道您可以实现多个接口并且只扩展一个类,但我确信与我提到的两个不同之处更多.
As far as I understand, the two concepts have the same rules except an abstract class is more flexible due to the method implementation ability. Also, I am aware you can implement multiple interfaces and only extend a single class but I'm sure there are more differences than the two I mentioned.
请查看这两个代码片段,并举例说明我可以用每个示例做什么来让我想要或不想使用另一个.
Please look at the two snippets of code and give me an example what I can do with each of my examples that would make me want or not want to use the other.
abstract class Foo {
abstract public function getValue();
abstract public function setValue($value);
}
class myObj extends Foo {
function getValue() {
}
function setValue($value) {
}
}
界面
interface Foo {
public function getValue();
public function setValue($value);
}
class myObj implements Foo {
function getValue() {
}
function setValue($value) {
}
}
推荐答案
恢复思路(全局,不详细):
To resume the idea (globally, not in detail):
inheritance
是从某物扩展
的概念,并且可以选择添加一些新功能或覆盖一些现有功能(以不同的方式).但是使用继承,您与父级共享大部分代码.您是父母+其他一些东西.
is the notion to extend from something
, and optionally add some new feature or override some existing feature (to do differently). But using inheritance, you share a big part of code with the parent. You are a parent + some other things.
interface
代表一些能力(我们说一个类正在实现一个接口来表示它具有这些能力).一个接口可以由两个完全不同的类来实现,并且不共享它们的代码(它们实现的方法除外).当 A 和 B 实现接口 C 时,A 不是 B,B 也不是 A.
is representing some abilities (we says a class is implementing an interface to says that it has these abilities). An interface can be implemented by 2 classes which are completely different and do not share their code (except for methods they implements). When A and B are implementing interface C, A is not a B and B is not a A.
interface
的原因之一确实是让程序员可以做与多继承一样的事情,但没有多继承问题.
And one of the reason for interface
is indeed to allow programmer to do the same as they could do with multi-inheritance, but without multi-inheritance problems.
这个概念在一些编程语言中使用,比如 JAVA、PHP...
This notion is used in some programming languages like JAVA, PHP...
这篇关于抽象类与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!