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.
super
keywordWhen 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.
super
can keep the parent method from being overridden.
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.
// To access parent class variables
super.variable_name;
// To access parent class method
super.method_name();
In the example below, we use the super
keyword to access parent class variables.
// Creating Parent classclass ParentClass {String shot = "This is a shot on Super Keyword";}// Creating child classclass SubClass extends ParentClass {String shot = "Educative";// Accessing parent class variablevoid showMessage(){print(super.shot);print("$shot has ${shot.length} letters.");}}void main(){// Creating child class instanceSubClass myClass = new SubClass();// Calling child class methodmyClass.showMessage();}
The variable shot
belongs to the parent class ParentClass
and is accessed by SubClass
using super.shot
.
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 classvoid showMessage(){print("This is parent class method.");}}class SubClass extends ParentClass {void showMessage(){print("This is child class method.");// Calling parent class methodsuper.showMessage();}}void main(){// Creating the child class instanceSubClass myClass = new SubClass();myClass.showMessage();}
In the code above, the parent class’s method is called as super.showMessage()
in SubClass
.