Dart – Super keyword

In Dart, super keyword is used to refer immediate parent class object. It is used to call properties and methods of the superclass. It does not call the method, whereas when we create an instance of subclass than that of the parent class is created implicitly so super keyword calls that instance.

Advantages of super keyword:

  • It can be used to access the data members of parent class when both parent and child have member with same name.
  • It is used to prevent overriding the parent method.
  • It can be used to call parameterized constructor of parent class.

EXAMPLE

  1. // Base class Super   
  2. class Super   
  3. {   
  4.     void display()   
  5.     {   
  6.         print(“This is the super class method”);   
  7.     }   
  8. }   
  9.   
  10. // Child class inherits Super  
  11. class Child extends Super   
  12. {   
  13.     void display()   
  14.     {   
  15.         print(“This is the child class”);   
  16.     }   
  17.   
  18.     // Note that message() is only in Student class   
  19.     void message()   
  20.     {   
  21.         // will invoke or call current class display() method   
  22.         display();   
  23.   
  24.         // will invoke or call parent class displa() method   
  25.         super.display();   
  26.     }   
  27. }   
  28.   
  29. void main() {  
  30.  // Creating object of sub class  
  31. Child c = new Child();   
  32. // calling display() of Student   
  33. c.message();   
  34.     }   

Output

This is the child class method
This is the super class method

Explanation -
In the above code, we created the function with the same name in both parent class and child class. The display() method is present in both parent class and child class that means It is a situation of method overriding.
So we created a message() method in the child class, inside it, we called parent class method using the super keyword, and then created the object of the child class. Using the object, we called the message() method that printed both display() methods statements to the screen.

		

Leave a comment

Your email address will not be published. Required fields are marked *