Constructor
- You can create an object using a constructor.
- Constructor names can be either ClassName or ClassName.identifier.
- Some classes provide constant constructors.
- The most common form of constructor, the generative constructor, creates a new instance of a class.
- Constructors aren’t inherited.
Invoking a non-default superclass constructor
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person does not have a default constructor; you must call super.fromJson(data).
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
main() {
var emp = new Employee.fromJson({});
// Prints:
// in Person
// in Employee
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}
(emp as Person).firstName = 'Bob';
}
Redirecting constructors
Related concepts
→
Constructor
→