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 Gfg class Shot{ // Creating property of the class Shot String shot1; // Creating Constructor Shot() { // Whenever constructor is called // this statement will be executed print('Constructor was called'); } // Creating Function inside class void display(){ print("This is a shot on $shot1"); } } void main() { // Creating Instance of class Shot shot = new Shot(); shot.shot1 = 'Constructor in Dart'; // Calling function name display() // using object of the class shot shot.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 Shot class Shot{ // Creating Constructor Shot() { print('This is the default constructor'); } } void main() { // Creating Instance of class Shot 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 Shot class Shot{ // Creating parameterized Constructor Shot(String title) { print("This is the $title constructor"); } } void main() { // Creating Instance of class Shot 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 Person class Person{ // Creating parameterized Constructor Person.detailConstructor(String name) { print("$name lives on the highland."); } // Creating default constructor Person.detailConstructor2() { print("Maria is a Flutter developer"); } } void main() { // Creating Instance of class Person p1 = new Person.detailConstructor("Maria"); Person p2 = new Person.detailConstructor2(); }
RELATED TAGS
CONTRIBUTOR
View all Courses