Dart - super关键字

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

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

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

    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

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

    技术教程推荐

    如何设计一个秒杀系统 -〔许令波〕

    许式伟的架构课 -〔许式伟〕

    玩转webpack -〔程柳锋〕

    分布式技术原理与算法解析 -〔聂鹏程〕

    MongoDB高手课 -〔唐建法(TJ)〕

    如何看懂一幅画 -〔罗桂霞〕

    Spark核心原理与实战 -〔王磊〕

    零基础入门Spark -〔吴磊〕

    徐昊 · AI 时代的软件工程 -〔徐昊〕

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