【问题标题】:Why to pass values to the super class? subclass to super为什么要将值传递给超类?子类到超级
【发布时间】:2020-01-08 16:04:43
【问题描述】:

我正在检查Equatable package“如何使用”示例,它们将值传递给 super 类,而这个主题对我来说就像一个盲点,我到处都能看到它:

import 'package:equatable/equatable.dart';

class Person extends Equatable {
  final String name;

  // why? what's happening behind the scene here?
  Person(this.name) : super([name]);
}

另一个例子

@immutable
abstract class MyEvent extends Equatable {
  MyEvent([List configs = const []]) : super(configs);
}

1- 我们为什么要这样做?为什么要为抽象事物传递值?蓝图?这个有什么用?

2- 为什么有时开发人员会像这样为抽象类传递值?

3- 幕后发生了什么?

4- 这样的代码有什么用例?

非常感谢。

【问题讨论】:

  • @Nexevis 嗨,事实上我知道这一点,我的问题是为什么要为抽象的东西传递值?蓝图?这个有什么用?

标签: oop flutter dart object-oriented-analysis


【解决方案1】:

一个抽象的类并不排除它在 Dart 中有一些具体的成员。

以下面的类为例:

abstract class Foo {
  Foo(this.value);

  final int value;

  @override
  String toString() => value.toString();
}

虽然它是抽象的,但它具有属性value 的具体实现,通过自定义构造函数进行初始化。

而且由于参数是必需的,子类必须像这样调用超级构造函数:

class Subclass extends Foo {
  Subclass(): super(42); 
}

【讨论】:

  • 我明白了。 “因为需要参数”是关键。因此,这是将attribute 标记为仅允许参数化构造函数所需的唯一方法,因此The superclass 'Foo' doesn't have a zero argument constructor. 将是结果。非常感谢。
  • 构造函数参数不是必须的。
猜你喜欢
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多