Super Keyword
- Definition
- Accessing base class variables
- Invoking base class method
- Invoking base class constructor
The concept of super keyword comes with the idea of inheritance in Dart. Suppose you have a member variable or method of the same name in the derived class as you do in the base class.
When referring to that variable/method, how would the program know which one are you referring to: the base class or the derived class?
This is where super comes into play. The super keyword in Dart acts like a
It’s mainly used when we want to access a variable, method, or constructor in the base class, from the derived class.
When we have the data members of the same name in both the base and derived class, we can use the super keyword to access the base class member in the derived class.
Example:
class Base {
int nb = 25;
}
class Derived extends Base {
int nb = 50;
void printNb() {
print("Base nb : ${super.nb}");
print("Derived nb : $nb");
}
void setSuperNb(int x) {
super.nb = x;
}
}
void main() {
var object = Derived();
object.printNb();
object.nb = 60;
object.printNb();
object.setSuperNb(11);
object.printNb();
}
Derived nb : 50
Base nb : 25
Derived nb : 60
Base nb : 11
Derived nb : 60
When the name of a function is the same in both the base and derived class, the super keyword can be used to invoke the base class function in the derived class.
Example:
class Base {
void speak() {
print("Hi! I am from the base Class");
}
}
class Derived extends Base {
void speak() {
print("Hello! I am from the derived Class");
}
void listen() {
super.speak();
speak();
}
}
void main() {
var object = Derived();
object.listen();
}
Hello! I am from the derived Class
The super keyword can also be used to invoke the parent class constructor, both parameterized and empty, in the derived class.
Example:
class Base {
Base() {
print("Base Constructor");
}
}
class Derived extends Base {
Derived() : super() {
print("Derived Constructor");
}
}
void main() {
var object = Derived();
}
Derived Constructor