Class Constructor
A constructor is a special function of the class that is responsible for initializing the variables of the class.
When we create the object of class, then constructor is automatically called.
You can create an object using a constructor. Constructor names can be either ClassName or ClassName.identifier .
A constructor is a function and hence can be parameterized .
However, unlike a function, constructors cannot have a return type .
- Default constructors
- Parameter Constructor
- Named Constructors
- Initializer list
If you don’t declare a constructor, a default constructor is provided for you. The default constructor has no arguments and invokes the no-argument constructor in the superclass (You will more understand it in super constructor lesson) .
A constructor has the same name as its class name and it doesn't return any value.
Suppose if we have class Person then the constructor name should be also Person.
class Person {
String name;
int id;
Person(name1, id1) {
name = name1;
id = id1;
print("The name and the id have been initialized");
}
}
Note :
We can also create a constructor without arguments.
class Person {
String name;
int id;
Person() {
print("New Object from person has been created");
}
}
Use a named constructor to implement multiple constructors for a class or to provide extra clarity:
class Person {
String name;
int id;
Person(name1, id1) {
name = name1;
id = id1;
}
Person.onlyname(name1) {
name = name1;
id = 0;
}
Person.unknown() {
name = "NaN";
id = 0;
}
}
void main() {
var p1 = Person("tom", 464385190);
print(p1.name);
print(p1.id);
print("--------");
var p2 = Person.onlyname("John");
print(p2.name);
print(p2.id);
print("--------");
var p3 = Person.unknown();
print(p3.name);
print(p3.id);
}
464385190
--------
John
0
--------
NaN
0
You can also initialize instance variables before the constructor body runs. Separate initializers with commas.
class Person {
String name;
int id;
Person(n, i) : name = n, id = i {
print("New person called $name has been created");
}
}
void main() {
var p1 = Person("tom", 464385190);
}