如何在Dart中定义接口?

IAm*_*aja 30 oop api inheritance interface dart

在Java中,我可能有一个接口IsSilly和一个或多个实现它的具体类型:

public interface IsSilly {
    public void makePeopleLaugh();
}

public class Clown implements IsSilly {
    @Override
    public void makePeopleLaugh() {
        // Here is where the magic happens
    }
}

public class Comedian implements IsSilly {
    @Override
    public void makePeopleLaugh() {
        // Here is where the magic happens
    }
}
Run Code Online (Sandbox Code Playgroud)

Dart中这段代码的等价物是什么?

仔细阅读关于课程的官方文档后,Dart似乎没有本机interface类型.那么,一般的Dartisan如何完成界面隔离原则呢?

Ale*_*uin 51

在Dart中有隐式接口的概念.

每个类都隐式定义一个接口,该接口包含该类的所有实例成员及其实现的任何接口.如果要在不继承B实现的情况下创建支持B类API的A类,则A类应实现B接口.

类通过在implements子句中声明它们然后提供接口所需的API来实现一个或多个接口.

所以你的例子可以像Dart一样翻译:

abstract class IsSilly {
  void makePeopleLaugh();
}

class Clown implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以定义抽象静态方法或抽象命名构造函数? (2认同)
  • 我会比这个简单的例子更感激 (2认同)

jos*_*jan 10

混淆通常是因为不存在像 java 和其他语言那样的“接口”这个词。类声明本身就是 Dart 中的接口。

在 Dart 中,每个类都定义了一个隐式接口,就像其他人说的那样。那么……关键是:类应该使用 implements 关键字才能使用接口。

abstract class IsSilly {
  void makePeopleLaugh();
}

//Abstract class
class Clown extends IsSilly {   
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

//Interface
class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}
Run Code Online (Sandbox Code Playgroud)


Pix*_*ant 8

在Dart中,每个类都定义了一个隐式接口.您可以使用抽象类来定义无法实例化的接口:

abstract class IsSilly {
    void makePeopleLaugh();
}

class Clown implements IsSilly {

    void makePeopleLaugh() {
        // Here is where the magic happens
    }

}

class Comedian implements IsSilly {

    void makePeopleLaugh() {
        // Here is where the magic happens
    }

}
Run Code Online (Sandbox Code Playgroud)


Roh*_*eja 5

其他答案在告知方法接口方面做得很好。

如果您正在寻找具有属性的接口,则可以使用 getter:

abstract class AppColors {
  Color get primary;

  Color get secondary;
}
Run Code Online (Sandbox Code Playgroud)
class AppColorsImpl implements AppColors {

  @override
  Color get primary => Colors.red;

  @override
  Color get primary => Colors.blue;
}
Run Code Online (Sandbox Code Playgroud)

是的,您可以组合一个接口来同时具有属性和方法。

--- 更新 --- Dart 3.0 版本添加了对 Class 修饰符的支持:

https://dart.dev/language/class-modifiers