Super Keyword in Dart:
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.
Syntax:
// To access parent class variables
super.variable_name;
// To access parent class method
super.method_name();
Example #1: Showing the flow of object creation in inheritance.
class SuperGeek {
SuperGeek()
{
print( "You are inside Parent constructor!!" );
}
}
class SubGeek extends SuperGeek {
SubGeek()
{
print( "You are inside Child constructor!!" );
}
}
void main()
{
SubGeek geek = new SubGeek();
}
|
Output:
You are inside Parent constructor!!
You are inside Child constructor!!
Example #2: Accessing parent class variables
class SuperGeek {
String geek = "Geeks for Geeks" ;
}
class SubGeek extends SuperGeek {
void printInfo()
{
print( super .geek);
}
}
void main()
{
SubGeek geek = new SubGeek();
geek.printInfo();
}
|
Output:
Geeks for Geeks
Example #3: Accessing parent class methods
class SuperGeek {
void printInfo()
{
print( "Welcome to Gfg!!\nYou are inside parent class." );
}
}
class SubGeek extends SuperGeek {
void info()
{
print( "You are calling method of parent class." );
super .printInfo();
}
}
void main()
{
SubGeek geek = new SubGeek();
geek.info();
}
|
Output:
You are calling method of parent class.
Welcome to Gfg!!
You are inside parent class.
This Keyword in Dart:
While super keyword is used to call parent class, this keyword is used to call the class itself.
Advantages of this keyword:
- It can be used to call instance variable of current class.
- It can be used to set the values of the instance variable.
- It can be used to return the current class instance.
Using this keyword in Dart –
class Geek {
String geek_info;
Geek(String info)
{
this .geek_info = info;
}
void printInfo()
{
print( "Welcome to $geek_info" );
}
}
void main()
{
Geek geek = new Geek( "Geeks for Geeks" );
geek.printInfo();
}
|
Output:
Welcome to Geeks for Geeks