Constructors are a type of method for initializing an object when it is created in a program.
When an object is created in object-oriented programming, the constructor is automatically called, whether or not it’s explicitly defined.
Every class has a default constructor that is built by the compiler when the class is called, and each class can optionally define its own constructor.
The constructor and other class methods have several significant differences.
class_name( [ parameters ] ){
// Constructor Body
}
// Dart Program to create a constructor// Creating Class named Gfgclass Shot{// Creating property of the class ShotString shot1;// Creating ConstructorShot() {// Whenever constructor is called// this statement will be executedprint('Constructor was called');}// Creating Function inside classvoid display(){print("This is a shot on $shot1");}}void main() {// Creating Instance of classShot shot = new Shot();shot.shot1 = 'Constructor in Dart';// Calling function name display()// using object of the class shotshot.display();}
There are three types of constructors:
The default constructor is a constructor that does not have any parameters.
The syntax is given below:
class ClassName {
ClassName() {
// constructor body
}
}
// Creating Class named Shotclass Shot{// Creating ConstructorShot() {print('This is the default constructor');}}void main() {// Creating Instance of classShot s1 = new Shot();}
The parameterized constructor is the constructor that takes parameters. It’s used to set the value of instance variables.
The syntax is given below:
class ClassName {
ClassName(parameter_list){
// constructor body
}
}
Note: Two constructors with the same name but different parameters cannot exist. The compiler will throw an error.
// Creating Class named Shotclass Shot{// Creating parameterized ConstructorShot(String title) {print("This is the $title constructor");}}void main() {// Creating Instance of classShot s1 = new Shot("parameterized");}
This sort of constructor is the solution to the problem of having numerous constructors with the same name. It allows you to create several constructors, each with its own name.
The syntax is given below:
className.constructor_name(param_list)
Multiple constructors in a single class can be declared using named constructors.
// Creating Class Personclass Person{// Creating parameterized ConstructorPerson.detailConstructor(String name) {print("$name lives on the highland.");}// Creating default constructorPerson.detailConstructor2() {print("Maria is a Flutter developer");}}void main() {// Creating Instance of classPerson p1 = new Person.detailConstructor("Maria");Person p2 = new Person.detailConstructor2();}