无涯教程-Dart - super关键字

196 阅读2分钟

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

    Super关键字

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

    Super.varName

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

    // 父类 Car 
    class Car
    { 
        int speed = 180; 
    } 
    

    // 子类 Bike 继承 Car class Bike extends Car { int speed = 110;

    </span><span class="kwd">void</span><span class="pln"> display</span><span class="pun">()</span><span class="pln"> 
    </span><span class="pun">{</span><span class="pln"> 
        </span><span class="com">//基类的打印变量</span><span class="pln">
        </span><span class="kwd">print</span><span class="pun">(</span><span class="str">"The speed of car: ${super.speed}"</span><span class="pun">);</span><span class="pln">
    </span><span class="pun">}</span><span class="pln"> 
    

    } 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"); }

    </span><span class="com">//请注意,message()仅在Child类中</span><span class="pln">
    </span><span class="kwd">void</span><span class="pln"> message</span><span class="pun">()</span><span class="pln"> 
    </span><span class="pun">{</span><span class="pln"> 
    	</span><span class="com">// 将调用或调用当前类的display()方法</span><span class="pln">
    	display</span><span class="pun">();</span><span class="pln"> 
    
    	</span><span class="com">// 将调用或调用父类的display()方法</span><span class="pln">
    	</span><span class="kwd">super</span><span class="pun">.</span><span class="pln">display</span><span class="pun">();</span><span class="pln"> 
    </span><span class="pun">}</span><span class="pln"> 
    

    }

    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

    参考链接

    www.learnfk.com/dart-progra…