小编典典

接口和抽象类有什么区别?

oop

接口和抽象类有什么区别?


阅读 226

收藏
2022-02-14

共1个答案

小编典典

接口

接口是一种契约:编写接口的人说,“嘿,我接受这样的东西”,而使用接口的人说:“好吧,我写的类是这样的”。

接口是一个空壳。只有方法的签名,这意味着方法没有主体。界面什么都做不了。这只是一个模式。

例如(伪代码):

// 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;
    }
}

实现一个接口消耗的 CPU 很少,因为它不是一个类,只是一堆名称,因此不需要进行任何昂贵的查找。它在重要时很棒,例如在嵌入式设备中。


抽象类

与接口不同,抽象类是类。它们的使用成本更高,因为当您从它们继承时需要进行查找。

抽象类看起来很像接口,但它们还有更多的东西:您可以为它们定义行为。更像是一个人说,“这些类应该是这样的,它们有共同点,所以填空! ”。

例如:

// 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");
    }
}

执行

虽然抽象类和接口应该是不同的概念,但实现有时会使这种说法不真实。有时,它们甚至不是您认为的那样。

在 Java 中,这个规则被强制执行,而在 PHP 中,接口是没有声明方法的抽象类。

在 Python 中,抽象类更像是一种可以从 ABC 模块获得的编程技巧,并且实际上使用的是元类,因此也使用了类。接口与这种语言中的鸭子类型更相关,它是约定和调用描述符的特殊方法(method 方法)的混合。

与编程一样,有另一种语言的理论、实践和实践:-)

2022-02-14