抽象类与接口 [英] 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
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
表示一些能力(我们说一个类是实现一个接口,表示它具有这些能力)。接口可以由2个类实现,这两个类完全不同并且不共享它们的代码(它们实现的方法除外)。当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 <的原因之一/ code>确实允许程序员执行与多继承相同的操作,但没有多继承问题。
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屋!