如何在Dart中调用超级构造函数?

Edu*_*pat 57 inheritance constructor extends superclass dart

如何在Dart中调用超级构造函数?是否可以调用命名的超级构造函数?

Edu*_*pat 75

是的,语法接近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);  
}
Run Code Online (Sandbox Code Playgroud)


Sob*_*had 22

这是我与您共享的文件,按原样运行。您将学习如何调用超级构造函数,以及如何调用超级参数化构造函数。

/ 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");
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

带有可选参数的构造函数的情况

class Foo {
  String a;
  int b;
  Foo({this.a, this.b});
}

class Bar extends Foo {
  Bar({a,b}) : super(a:a, b:b);
}
Run Code Online (Sandbox Code Playgroud)

  • 在 Bar 的构造函数中,“a”和“b”参数是“动态”类型。您错过了静态类型语言的优点。 (2认同)

use*_*610 5

我可以调用超类的私有构造函数吗?

是的,但仅当您创建的超类和子类位于同一个库中时.(由于私有标识符在整个库中可见,因此它们被定义).私有标识符是以下划线开头的标识符.

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);
}
Run Code Online (Sandbox Code Playgroud)