oop - 为什么要将值传递给超类?子类到超级
问题描述
我正在检查Equatable 包“如何使用”示例,它们将值传递给超类,这个主题对我来说就像一个盲点,我到处都能看到:
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-这种代码的用例是什么?
多谢。
解决方案
一个抽象的类并不排除它在 Dart 中有一些具体的成员。
以下面的类为例:
abstract class Foo {
Foo(this.value);
final int value;
@override
String toString() => value.toString();
}
虽然它是抽象的,但它具有属性的具体实现,value
通过自定义构造函数进行初始化。
而且由于参数是必需的,子类必须像这样调用超级构造函数:
class Subclass extends Foo {
Subclass(): super(42);
}
推荐阅读
- java - 检查字符串的字符
- excel - 将多个csv文件批量转换为excel文件的快速方法
- python - Python从多行不同长度的字符求和
- java - 使用 String.format 从右侧获取字符串
- vim - VSCodeVim 键重映射
- reactjs - 在屏幕之间来回切换会导致双导航栏
- javascript - 高精度html5媒体播放器
- javascript - 我正在从表单创建一个 URL 字符串。如何根据我拥有的内容对 URL 进行编码?
- php - Laravel 5.6 - 使用 Eloquent 在相关表的日期时间字段中返回最新日期的问题
- r - 对因子进行 t.test