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
- // Base class Super
- class Super
- {
- void display()
- {
- print(“This is the super class method”);
- }
- }
- // Child class inherits Super
- class Child extends Super
- {
- void display()
- {
- print(“This is the child class”);
- }
- // Note that message() is only in Student class
- void message()
- {
- // will invoke or call current class display() method
- display();
- // will invoke or call parent class displa() method
- super.display();
- }
- }
- void main() {
- // Creating object of sub class
- Child c = new Child();
- // calling display() of Student
- c.message();
- }
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.