flutter+Dart 类的继承extends with implements (九)

主要涉及到三个关键字 extends、 with、 implements 。

extends是类的继承中最普遍的方式,如要结合后面两个关键字使用,根据文档,需要保证操作顺序:extends,mixins,implements。示例如下:

class ThingsboardAppState extends State
    with TickerProviderStateMixin
    implements TbMainDashboardHolder

1 继承(extends)

dart中的继承规则:

  • 使用extends关键词来继承父类
  • 子类会继承父类里面可见的属性和方法 但是不会继承构造函数
  • 子类能复写父类的方法 getter和setter
  • 子类重写超类的方法,要用@override
  • 子类调用超类的方法,要用super
  • 子类可以继承父类的非私有变量 (类中私有变量和函数的定义:名称前面带_)

2 混合 mixins (with)

  mixins的中文意思是混入(两个类混合在一起),就是在类中混入其他功能。简单的理解,就是在现有类的基础上,引入一些新的变量和方法。

  • 作为mixins的类只能继承自Object,不能继承其他类
  • 作为mixins的类不能有构造函数
  • 一个类可以mixins多个mixins
  • mixins不是继承,也不是接口,而是一种全新的特性。

3 接口实现(implements)

        接口的实现,基于定义的一个抽象类,抽象类中仅定义方法,没有具体的实现,子类通过implements的方法,在子类中实现具体的方法。

定义一个工厂类的示例代码:

abstract class TickerProvider {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const TickerProvider();

  /// Creates a ticker with the given callback.
  ///
  /// The kind of ticker provided depends on the kind of ticker provider.
  @factory
  Ticker createTicker(TickerCallback onTick);
}

子类实现的示例代码:

mixin TickerProviderStateMixin on State implements TickerProvider {
  Set? _tickers;

  @override
  Ticker createTicker(TickerCallback onTick) {
    if (_tickerModeNotifier == null) {
      // Setup TickerMode notifier before we vend the first ticker.
      _updateTickerModeNotifier();
    }
///...

混合继承类的定义:

class ThingsboardAppState extends State
    with TickerProviderStateMixin
    implements TbMainDashboardHolder

你可能感兴趣的:(flutter学习,flutter,android)