【发布时间】:2012-10-27 15:29:46
【问题描述】:
如何在 Dart 中调用超级构造函数?是否可以调用命名的超级构造函数?
【问题讨论】:
标签: inheritance constructor dart superclass extends
如何在 Dart 中调用超级构造函数?是否可以调用命名的超级构造函数?
【问题讨论】:
标签: inheritance constructor dart superclass extends
这是我与您共享的文件,请按原样运行。您将学习如何调用超级构造函数,以及如何调用超级参数化构造函数。
/ Objectives
// 1. Inheritance with Default Constructor and Parameterised Constructor
// 2. Inheritance with Named Constructor
void main() {
var dog1 = Dog("Labrador", "Black");
print("");
var dog2 = Dog("Pug", "Brown");
print("");
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 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: ");
}
【讨论】:
带有可选参数的构造函数的情况
class Foo {
String a;
int b;
Foo({this.a, this.b});
}
class Bar extends Foo {
Bar({a,b}) : super(a:a, b:b);
}
【讨论】:
是的,是的,语法接近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() 呼叫指南背后的动机。
【讨论】:
由于 dart 支持将类实现为接口 (Implicit interfaces),如果您实现则不能调用父构造函数,您应该使用 extends。 如果您使用 implements 将其更改为 extends 并使用 Eduardo Copat 的解决方案。
【讨论】:
是的,但前提是您创建的超类和子类在同一个库中。 (因为私有标识符在它们定义的整个库中都是可见的)。私有标识符是以下划线开头的标识符。
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);
}
【讨论】: