Given this code:
abstract class Animal {
String name;
Animal (String this.name) {
}
}
class Dog extends Animal {
// Why does this fail
Dog() {
super("Spot");
print("Dog was created");
}
// Compared to this
// Dog() : super("Spot");
}
According to multiple docs:
You can call the super class' constructor with the following syntax:
Dog() : super("Spot");
I assume this is some kind of a shortcut syntax to quickly call the super class' constructor. But what if I also want to do additional things in the Dog's constructor, such as calling print
.
Why doesn't this work, and what is the proper way to write the code?
// Why does this fail
Dog() {
super("Spot");
print("Dog was created");
}
In dart, the subclass can inherit all the variables and methods of the parent class, with the use of extends keyword but it can't inherit constructor of the parent class. To do so we make use of super constructor in the dart. There are two ways to call super constructor: Implicitly.
Syntax: // To access parent class variables super. variable_name; // To access parent class method super. method_name();
super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
You can call super
in this way:
abstract class Animal {
String name;
Animal (String this.name);
}
class Dog extends Animal {
Dog() : super('Spot') {
print("Dog was created");
}
}
void main() {
var d = new Dog(); // Prints 'Dog was created'.
print(d.name); // Prints 'Spot'.
}
If you want execute code before the super
you can do it like that:
abstract class Animal {
String name;
Animal (this.name);
}
class Cat extends Animal {
String breed;
Cat(int i):
breed = breedFromCode(i),
super(randomName());
static String breedFromCode(int i) {
// ...
}
static String randomName() {
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With