[英]How do I call on the super class' constructor and other statements in Dart?
[英]how can i initialize super class variables in dart language?
只是我必須給孩子和家長上課
我是飛鏢語言的新手,我只需要從子類分配超類屬性
這是超類結構
class Trip{
final int id;
final String title;
final double price;
Trip({this.id,this.title,this.price});
}
這是兒童班
class FullTrip extends Trip{
final String data;
FullTrip({this.data}) : super(id:id,title:title,price:price);
}
確保這根本不起作用
問題是:我如何從 FullTrip 初始化實例並為 FullTrip 和 Trip(超類)傳遞變量
提前致謝
您需要重復子類中的參數。
class FullTrip extends Trip{
final String data;
FullTrip({this.data, int id, String title, double price}) : super(id:id,title:title,price:price);
}
有關於為構造函數減少此類樣板的討論,但據我所知,還沒有任何決定。
用戶super-parameters
,在 Dart 2.17
中添加。 例如,假設這是您的班級:
class Parent {
Parent({
int? i,
bool b = false,
required String s,
});
}
之前你必須做這樣的事情:
class Child extends Parent {
Child({
int? i,
bool b = false,
required String s,
}) : super(
i: i,
b: b,
s: s,
);
}
但是現在您可以擺脫那些樣板代碼。
class Child extends Parent {
Child({
super.i,
super.b = false,
required super.s,
});
}
如果您想在編譯之前在子類中重新初始化擴展或實現的上類的非私有變量,只需使用@override
。 看這個例子
(如果您想嘗試該代碼,請記住它支持空安全性。如果您的測試不支持,只需刪除?
符號。)
class Go {
String? name = "No name";
}
class Foo implements Go { //use either implements or extends
@override
String? name = "Foo";
}
class Doo extends Go { //use either implements or extends
@override
String? name = "Doo";
}
用例示例:在上面的代碼中,您可以看到在我們的上層類中,我們有這個String name
變量。 然后在子類中我們可以簡單地覆蓋該變量。 之后,在 main 中,我們現在可以做一些事情,比如遍歷List<Go>
,訪問我們想要的內容,然后觸發一些事情,比如打印名稱:
void main() {
List<Go> foos = [
Go(),
Foo(),
Doo(),
];
for(Go x in foos){
print(x.name);
}
}
輸出:
No name
Foo
Doo
如果您使用extends
或implements
關鍵字,這將有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.