Dart - super关键字

Dart - super关键字 首页 / Dart入门教程 / Dart - super关键字

Super关键字用于表示当前子类的即时父类对象。它用于调用其子类中的超类方法,超类构造函数。超级关键字的主要目标是识别具有相同方法名称的父类和子类之间的混淆,它还用于调用超类属性和方法。

    Super关键字

    当子类具有与超类变量相同的名称变量时,会出现这种情况。因此,Dart编译器有可能会产生歧义。然后,super关键字可以访问其子类中的超类变量。语法在下面给出。

    Super.varName

    我们可以通过以下示例更加了解。

    链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-super-keyword.html

    来源:LearnFk无涯教程网

    // 父类 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关键字在子类中使用父类方法。

    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关键字访问父类构造函数。超级关键字可以根据情况调用参数化和非参数化构造函数。

    :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

    祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

    技术教程推荐

    从0开始学游戏开发 -〔蔡能〕

    技术管理实战36讲 -〔刘建国〕

    代码精进之路 -〔范学雷〕

    趣谈Linux操作系统 -〔刘超〕

    Linux实战技能100讲 -〔尹会生〕

    全栈工程师修炼指南 -〔熊燚(四火)〕

    Electron开发实战 -〔邓耀龙〕

    如何成为学习高手 -〔高冷冷〕

    徐昊 · TDD项目实战70讲 -〔徐昊〕

    好记忆不如烂笔头。留下您的足迹吧 :)