In this tutorial you will learn about the Dart super Keyword and its application with practical example.
Dart super Keyword
The super keyword is a reference variable which is used to refer immediate parent class object. It is used to refer the superclass properties and methods. This is possible because when we create an instance of subclass, an instance of its parent class is created implicitly which we can refer using the super keyword. The most common use of the super keyword is to eliminate the ambiguity between superclasses and subclasses that have variables and methods with the same name.
Usage of super Keyword
1) The super keyword can be used to access the data members of parent class when both parent and child class have member with same name.
2) The super keyword can be used to access the method of parent class when child class has overridden that method. 3) The super keyword can be used to explicitly call the no-arg and parameterized constructor of parent class
Use super keyword to access parent class variables
When you have a variable in sub class which is already exists in its super class; then the super keyword can be used to access variable in super class.
Syntax:-
1 |
super.varName |
Example:-
In the following program, we have a variable num declared in the SubClass, the variable with the same name is already present in the SuperClass.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class SuperClass { int num = 50; } class SubClass extends SuperClass { /* The same variable num is declared in the SubClass * which is already present in the SuperClass */ int num = 100; void printNumber(){ print(super.num); } } void main(){ SubClass obj= new SubClass(); obj.printNumber(); } |
Output:-
1 |
50 |
Here, if we use print(num); instead of print(super.num); it will print 100 instead of 50.
Use super keyword to invoke parent class method
When a subclass contains a method already present in the superclass then it is called method overriding. In method overriding call to the method from subclass object will always invoke the subclass version of the method. However, using the super keyword we are allowed to invoke superclass version of the method.
Syntax:-
1 |
super.methodName |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class SuperClass { void display(){ print("Parent class method"); } } class SubClass extends SuperClass { //Overriding method void display(){ print("Child class method"); } void printMsg(){ //This would call subclass method display(); //This would call superclass method super.display(); } } void main(){ SubClass obj= new SubClass(); obj.printMsg(); } |
Output:-
1 2 |
Child class method Parent class method |
Note:-When subclass doesn’t override the superclass method then there is no need to use the super keyword to call the superclass method.