接口(interface)和抽象类到底有什么区别?
最佳答案
接口(interface)
接口(interface)是一个契约:编写接口(interface)的人说,“嘿,我接受这样的事情”,使用接口(interface)的人说“< em>好吧,我写的类看起来就是这样的”。
接口(interface)是一个空壳。只有方法的签名,这意味着方法没有主体。界面什么也做不了。这只是一个模式。
例如(伪代码):
// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();
int getFuel();
}
// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{
int fuel;
void run()
{
print("Wrroooooooom");
}
int getFuel()
{
return this.fuel;
}
}
实现一个接口(interface)消耗很少的CPU,因为它不是一个类,只是一堆名称,因此不需要做任何昂贵的查找。当它很重要时,例如在嵌入式设备中,它就很棒。
<小时/>抽象类
与接口(interface)不同,抽象类是类。它们的使用成本更高,因为当您继承它们时需要进行查找。
抽象类看起来很像接口(interface),但它们还有更多的东西:您可以为它们定义行为。更多的是一个人说,“这些类应该看起来像那样,并且它们有共同点,所以填空!”。
例如:
// I say all motor vehicles should look like this:
abstract class MotorVehicle
{
int fuel;
// They ALL have fuel, so lets implement this for everybody.
int getFuel()
{
return this.fuel;
}
// That can be very different, force them to provide their
// own implementation.
abstract void run();
}
// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("Wrroooooooom");
}
}
<小时/>
实现
虽然抽象类和接口(interface)应该是不同的概念,但实现使该声明有时不真实。有时,他们甚至不是你想象的那样。
在 Java 中,这条规则被严格执行,而在 PHP 中,接口(interface)是没有声明方法的抽象类。
在 Python 中,抽象类更多地是一种可以从 ABC 模块中获得的编程技巧,并且实际上使用元类,因此也使用类。接口(interface)与这种语言中的鸭子类型更相关,它是调用描述符的约定和特殊方法(__method__ 方法)之间的混合。
与往常一样,编程也有理论、实践和另一种语言的实践:-)
关于oop - 接口(interface)和抽象类有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687678/