界面和抽象的公共功能

use*_*729 1 php interface abstract-function

在我看来,这两个interfaceabstract function非常相似,

这就像一个必须实施某些方法的订单,

那有什么区别?

Sar*_*raz 6

看看这个.

引用:(非常好的解释,电子满意)

接口

一个接口是一个契约:编写界面的人说"嘿,我接受看起来那样的东西",而使用界面的人说"好吧,我写的课看起来那样".

并且接口是一个空shell,只有方法的签名(name/params/return类型).这些方法不包含任何内容.界面无能为力.这只是一种模式.

EG(伪代码):

// I say all motor vehicles should look like that :
interface MotorVehicle
{
    void run();

    int getFuel();
}

// my team mate complies and write vehicle looking that way
class Car implements MotoVehicle
{

    int fuel;

    void run()
    {
        print("Wrroooooooom");
    }


    int getFuel()
    {
        return this.fuel;
    }
}
Run Code Online (Sandbox Code Playgroud)

实现一个接口消耗很少的CPU,因为它不是一个类,只是一堆名称,因此没有昂贵的查找.当它在嵌入式设备中很重要时非常棒.

抽象类

与接口不同,抽象类是类.使用起来比较昂贵,因为当你从它们继承时会有查找.

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

例如:

// I say all motor vehicles should look like that :
abstract class MotorVehicle
{

    int fuel;

    // they ALL have fuel, so why let others implement that ?
    // let's make it for everybody
    int getFuel()
    {
         return this.fuel;
    }

    // that can be very different, force them to provide their
    // implementation
    abstract void run();


}

// my team mate complies and write vehicle looking that way
class Car extends MotorVehicule
{
    void run()
    {
        print("Wrroooooooom");
    }
}
Run Code Online (Sandbox Code Playgroud)

通过:https://stackoverflow.com/users/9951/e-satis