📜  Dart的超级构造函数

📅  最后修改于: 2021-09-02 05:48:06             🧑  作者: Mango

在dart,子类可以继承父类的所有变量和方法,使用extends关键字,但不能继承父类的构造函数。为此,我们在dart使用了超级构造函数。调用超级构造函数有两种方式:

  1. 含蓄地
  2. 明确地

当显式调用时,我们使用超级构造函数作为:

Child_class_constructor() :super() {
...
}

隐式超:在这种情况下,当有子类的对象创建时,会隐式调用父类。这里我们没有使用超级构造函数,但是当调用子类构造函数时,它会调用默认的父类构造函数。

示例:调用不带参数的父构造函数。

Dart
// Dart program for calling parent
// constructor taking no parameter
class SuperGeek {
    
  // Creating parent constructor
  SuperGeek(){
    print("You are inside Parent constructor!!");
  }
}
   
class SubGeek extends SuperGeek {
    
  // Creating child constructor
  SubGeek(){
    print("You are inside Child constructor!!");
  }
}
   
void main() {
  SubGeek geek = new SubGeek();
}


Dart
class SuperGeek {
    
  // Creating parent constructor
  SuperGeek(String geek_name){
    print("You are inside Parent constructor!!");
    print("Welcome to $geek_name");
  }
}
   
class SubGeek extends SuperGeek {
    
  // Creating child constructor
  // and calling parent class constructor
  SubGeek() : super("Geeks for Geeks"){
    print("You are inside Child constructor!!");
  }
}
   
void main() {
  SubGeek geek = new SubGeek();
}


输出:

You are inside Parent constructor!!
You are inside Child constructor!!

显式超级:如果父构造函数是默认的,那么我们在隐式超级中调用它,但如果它接受参数,则调用超类,如上面提到的语法所示。

示例:调用带参数的父构造函数。

Dart

class SuperGeek {
    
  // Creating parent constructor
  SuperGeek(String geek_name){
    print("You are inside Parent constructor!!");
    print("Welcome to $geek_name");
  }
}
   
class SubGeek extends SuperGeek {
    
  // Creating child constructor
  // and calling parent class constructor
  SubGeek() : super("Geeks for Geeks"){
    print("You are inside Child constructor!!");
  }
}
   
void main() {
  SubGeek geek = new SubGeek();
}

输出:

You are inside Parent constructor!!
Welcome to Geeks for Geeks
You are inside Child constructor!!