Super关键字用于表示当前子类的即时父类对象。它用于调用其子类中的超类方法,超类构造函数。超级关键字的主要目标是识别具有相同方法名称的父类和子类之间的混淆,它还用于调用超类属性和方法。
当子类具有与超类变量相同的名称变量时,会出现这种情况。因此,Dart编译器有可能会产生歧义。然后,super关键字可以访问其子类中的超类变量。语法在下面给出。
Super.varName
我们可以通过以下示例更加了解。
// 父类 Car class Car { int speed = 180; } // 子类 Bike 继承 Car class Bike extends Car { int speed = 110; void display() { //基类的打印变量 print("The speed of car: ${super.speed}"); } } void main() { // 创建子类的对象 Bike b = new Bike(); b.display(); }
输出
The speed of car: 180
如前所述,Super关键字用于访问子类中的父类方法。如果子类和父类包含相同的名称,则可以使用Super关键字在子类中使用父类方法。
super.methodName;
让我们了解以下示例
// 基类超级 class Super { void display() { print("This is the super class method"); } } // 子类继承超级 class Child extends Super { void display() { print("This is the child class"); } //请注意,message()仅在Child类中 void message() { // 将调用或调用当前类的display()方法 display(); // 将调用或调用父类的display()方法 super.display(); } } void main() { //创建子类的对象 Child c = new Child(); //调用学生的display() c.message(); }
输出
This is the child class method This is the super class method
我们还可以使用super关键字访问父类构造函数。超级关键字可以根据情况调用参数化和非参数化构造函数。
:super();
让我们了解以下示例.
// 基类称为Parent class Parent { Parent() { print("This is the super class constructor"); } } // Child 继承 Parent class Child extends Parent { Child():super() //调用父类构造函数 { print("This is the sub class constructor"); } } void main() { //创建子类的对象 Child c = new Child(); }
输出
This is the super class constructor This is the sub class constructor
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)