What is the super keyword in Dart?

The super keyword in Dart is used to refer to the object of the immediate parent class of the current child class.

The super keyword is also used to call the parent class’s methods, constructor, and properties in the child class.

Benefits of the super keyword

  1. When both the parent and the child have members with the same name, super can be used to access the data members of the parent class.

  2. super can keep the parent method from being overridden.

  3. super can call the parent class’s parameterized constructor.

The main goal of the super keyword is to avoid ambiguity between parent and subclasses with the same method name.

Syntax

// To access parent class variables
super.variable_name;

// To access parent class method
super.method_name();

Code

Example 1

In the example below, we use the super keyword to access parent class variables.

// Creating Parent class
class ParentClass {
String shot = "This is a shot on Super Keyword";
}
// Creating child class
class SubClass extends ParentClass {
String shot = "Educative";
// Accessing parent class variable
void showMessage(){
print(super.shot);
print("$shot has ${shot.length} letters.");
}
}
void main(){
// Creating child class instance
SubClass myClass = new SubClass();
// Calling child class method
myClass.showMessage();
}

Explanation

The variable shot belongs to the parent class ParentClass and is accessed by SubClass using super.shot.

Example 2

In this example, we use the super keyword to access the parent class method.

When the parent and child classes have the same name, we can use the super keyword to call the parent class method from the child class.

class ParentClass {
// Creating a method in Parent class
void showMessage()
{
print("This is parent class method.");
}
}
class SubClass extends ParentClass {
void showMessage()
{
print("This is child class method.");
// Calling parent class method
super.showMessage();
}
}
void main(){
// Creating the child class instance
SubClass myClass = new SubClass();
myClass.showMessage();
}

Explanation

In the code above, the parent class’s method is called as super.showMessage() in SubClass.

Free Resources