Super Constructor
Dart Super Constructor
With the exception of the parent class constructor, the child class can inherit all of the parent’s methods, variables, and behaviors.& The super() constructor in a subclass can be used to call the superclass constructor. We have access to the superclass’s parameterized and non-parameterized constructors. In Dart, gaining access to the superclass constructor is a little bit different. Below is the syntax.
Syntax
SubClassConstructor():super() {
}
Implicit super
As is common knowledge, when we instantiate a class, the constructor is called automatically. The default (non-parameterized) constructor of the parent class is implicitly invoked when the subclass constructor is called when the object is created. To call the constructor of the superclass, we can utilize the super() constructor in our subclass. Let’s examine the next illustration.
Example
// Parent class
class Superclass {
Superclass(){
print("This is a superclass constructor");
}
}
class Subclass extends Superclass
{
Subclass(){
print("This is a subclass constructor");
}
display(){
print("Welcome to javatpoint");
}
}
void main(){
print("Dart Implicit Superclass constructor call");
// We create a object of sub class which will invoke subclass constructor.
// as well as parent class constructor.
Subclass s = new Subclass();
// Calling sub class method
s.display();
}
Output
Dart Implicit Superclass constructor example
This is a superclass constructor
This is a subclass constructor
Welcome to javatpoint
Explicit super
To explicitly invoke the superclass constructor in a subclass, we must call the super() constructor with an argument if the superclass constructor has any parameters. Let’s examine the next illustration.
Example
// Parent class
class Superclass {
Superclass(String msg){
print("This is a superclass constructor");
print(msg);
}
}
class Subclass extends Superclass
{
Subclass():super("We are calling superclass constructor explicitly "){
print("This is a subclass constructor");
}
display(){
print("Welcome to javatpoint");
}
}
void main(){
print("Dart Implicit Superclass constructor example");
// We create an object of sub class which will invoke subclass constructor.
// as well as parent class constructor.
Subclass s = new Subclass();
// Calling sub class method
s.display();
}
Output
Dart explicit Superclass constructor example
This is a parameterized superclass constructor
We are calling superclass constructor explicitly
This is a subclass constructor
Welcome to javatpoint