oop - 如何在 Dart 中定义接口(interface)?

标签 oop inheritance dart interface

在 Java 中,我可能有一个接口(interface) 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
    }
}

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

看完官方docs在类里面,Dart 似乎没有原生 interface类型。那么,一般的 Dartisan 是如何实现接口(interface)隔离原理的呢?

最佳答案

在 Dart 中有一个概念 implicit interfaces .

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces.


所以你的例子可以像这样在 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
  }
}

关于oop - 如何在 Dart 中定义接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791286/

相关文章:

Firebase SDK 安装问题 Flutter

inheritance - Dart:继承和 super 构造函数

java - 以编程方式调用 Java 类中的所有方法

c++ - 模板化类时模板不能是虚拟错误

Python:访问面向对象的变量?

opengl - 如何在函数调用中跟踪 OpenGL 状态?

php - 接口(interface)可以扩展其他类吗?

c++ - 从 C++ 中的父类(super class)数组访问子类方法?

java - 流畅的语法和继承

dart - 扩展图 block 时如何滚动 ExpansionTile/Listview?