在抽象类中将方法声明为可选方法

dev*_*ush 5 oop abstract-class interface dart

据我所知,在 Dart 中可以使用抽象类来声明“接口”或“协议”(如果您来自 Objective-c)。无论如何,我无法找到在抽象类/接口中声明可选方法的方法。

如果我在抽象类A 中声明一个方法,并让具体类B实现A,我会在编译器中收到警告。我希望能够将一个方法声明为可选的,或者至少提供一个默认实现,而无需在实现我的接口的类中“重新声明”它。

abstract class A{
   void abstractMethod();
}

class B implements A{
 //not implementing abstract method here gives a warning
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

这不是接口的工作方式。如果你的类声明要实现一个接口,那么这就是它必须做的。

可以拆分界面

abstract class A {
   void abstractMethod();
}

abstract class A1 extends A {
   void optionalMethod();
}


class B implements A {
 //not implementing abstract method here gives a warning
}
Run Code Online (Sandbox Code Playgroud)

只有当它声明要实施时,A1它才必须实施optionalMethod

或者,您可以扩展抽象类

abstract class A{
   void abstractMethod();
   void optionalMethod(){};
}

class B extends A {
 //not implementing abstract method here gives a warning
}
Run Code Online (Sandbox Code Playgroud)

then 只abstractMethod需要被覆盖,因为A不提供实现。