[英]How do I call on the super class' constructor and other statements in Dart?
[英]How do I call a super constructor in Dart?
如何在 Dart 中調用超級構造函數? 是否可以調用命名的超級構造函數?
是的,它的語法接近C# ,這里是一個同時包含默認構造函數和命名構造函數的示例:
class Foo {
Foo(int a, int b) {
//Code of constructor
}
Foo.named(int c, int d) {
//Code of named constructor
}
}
class Bar extends Foo {
Bar(int a, int b) : super(a, b);
}
class Baz extends Foo {
Baz(int c, int d) : super.named(c, d);
}
如果要在子類中初始化實例變量,則super()
調用必須位於初始化列表的最后。
class CBar extends Foo {
int c;
CBar(int a, int b, int cParam) :
c = cParam,
super(a, b);
}
您可以在/r/dartlang上閱讀此super()
調用指南背后的動機。
這是我與您共享的文件,按原樣運行它。 您將學習如何調用超級構造函數,以及如何調用超級參數化構造函數。
// Objectives
// 1. Inheritance with Default Constructor and Parameterised Constructor
// 2. Inheritance with Named Constructor
void main() {
var dog1 = Dog("Labrador", "Black");
var dog2 = Dog("Pug", "Brown");
var dog3 = Dog.myNamedConstructor("German Shepherd", "Black-Brown");
}
class Animal {
String color;
Animal(String color) {
this.color = color;
print("Animal class constructor");
}
Animal.myAnimalNamedConstrctor(String color) {
print("Animal class named constructor");
}
}
class Dog extends Animal {
String breed;
Dog(String breed, String color) : super(color) {
this.breed = breed;
print("Dog class constructor");
}
Dog.myNamedConstructor(String breed, String color) : super.myAnimalNamedConstrctor(color) {
this.breed = breed;
print("Dog class Named Constructor");
}
}
帶有可選參數的構造函數的情況
class Foo {
String a;
int b;
Foo({this.a, this.b});
}
class Bar extends Foo {
Bar({a,b}) : super(a:a, b:b);
}
是的,但前提是您創建的超類和子類在同一個庫中。 (因為私有標識符在它們定義的整個庫中都是可見的)。 私有標識符是以下划線開頭的標識符。
class Foo {
Foo._private(int a, int b) {
//Code of private named constructor
}
}
class Bar extends Foo {
Bar(int a, int b) : super._private(a,b);
}
由於 dart 支持將類實現為接口( 隱式接口),如果你實現了它就不能調用父構造函數,你應該使用extends 。 如果您使用工具,請將其更改為擴展並使用 Eduardo Copat 的解決方案。
class AppException implements Exception {
final _message;
final _prefix;
//constructor with optional & not named paramters
//if not the parameter is not sent, it'll be null
AppException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class FetchDataException extends AppException {
//redirecting constructor with a colon to call parent two optional parameters
FetchDataException([String msg]) : super(msg, "Error During Communication: ");
}
class BadRequestException extends AppException {
BadRequestException([msg]) : super(msg, "Invalid Request: ");
}
class UnauthorisedException extends AppException {
UnauthorisedException([msg]) : super(msg, "Unauthorised: ");
}
class InvalidInputException extends AppException {
InvalidInputException([String msg]) : super(msg, "Invalid Input: ");
}
如何在 Dart 中調用超級構造函數? 是否可以調用命名的超級構造函數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.