Dart编程中的super关键字


Dart中的super**关键字**用于引用父类对象的属性或方法。简单来说,它用于引用超类的**属性和方法**。

super关键字最重要的用途是消除具有相同名称的属性和方法的父类和子类之间的歧义。

当我们在Dart中创建一个子类的实例时,父类的实例也会隐式创建,super关键字能够调用父对象的属性和方法。

语法

super.varName or super.methodName

我们可以访问父类的变量和方法。

访问父类变量

我们可以访问在子类中也声明的父类变量。

示例

考虑以下示例:

在线演示

class Animal {
   int count = 30;
}

class Dog extends Animal {
   int count = 70;
   void printNumber(){
      print(super.count);
   }
}

void main(){
   Dog obj= new Dog();
   obj.printNumber();
}

在上面的例子中,我们有两个类**Animal**和**Dog**,其中Animal是父类(或超类),Dog是子类。需要注意的是,名为count的变量在超类和子类中都被声明,当我们使用**super.count**时,它将引用父类(超类)。

输出

30

访问父类方法

我们还可以访问可能也在子类中声明的父类方法。

示例

考虑以下示例:

在线演示

class Animal {
   void tellClassName(){
      print("Inside Animal Class");
   }
}

class Dog extends Animal {
   int count = 100;
   void tellClassName(){
      print("Inside Dog Class");
   }

   void printMessage(){
      tellClassName();
      super.tellClassName();
   }
}

void main(){
   Dog obj= new Dog();
   obj.printMessage();
}

输出

Inside Dog Class
Inside Animal Class

更新于:2021年5月24日

572 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.