super
- Dart course
- Intermediate
- Lesson 8/116
- 5 min
Learn to call the base class constructor with super.
super
A subclass constructor must explicitly call a base class constructor. The call uses the super keyword and sits in the initializer list position, after the colon.
Example: Dog(String name) : super(name);. Here super(name) calls the base class constructor Animal(String name) with the name argument. A parameterless base constructor is called automatically; in that case super() is not required. Parameterized base constructors require super(...) as the first item of the initializer list.
super and the initializer list
The super(...) call is part of the initializer list. When both field assignment and a super call are needed, they are joined with commas; super comes last.
Example: Puppy(String name, int age) : age = age, super(name);. Here age = age initializes the subclass field and super(name) calls the base constructor. After the colon, both are separated by commas. This shape lets you init subclass fields and pass data to the base constructor at once; the order matters.
Practice Add super to the Dog constructor
Keep the existing Animal class. Add a Dog(String name) : super(name); constructor to the Dog class. In main, create an instance with var d = Dog('Rex'); and call print(d.name).
Starter code
class Animal {
String name;
Animal(this.name);
}
class Dog extends Animal {
// Add a constructor that calls super(name)
}
void main() {
// Create a Dog instance and print d.name
}Sample solution
class Animal {
String name;
Animal(this.name);
}
class Dog extends Animal {
Dog(String name) : super(name);
}
void main() {
var d = Dog('Rex');
print(d.name);
}Expected output
Rex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the super call
class Dog extends Animal {
Dog(String name) : ____(name);
}
class Dog extends Animal {
Dog(String name) : super(name);
}
Explanation: super calls the base class constructor.
2 What does super(name) do?
- Creates a new base class instance
- Hides the name field
- Adds a name field to the subclass
- Calls the base constructor with the name argument Correct answer
Explanation: super(name) calls the base constructor with name.
3 Match the super parts
| Term | Meaning |
|---|---|
super |
Base class reference |
: |
Initializer list start |
name |
Argument |