Constructors in DART language
In this article, I am going to explain about constructors in dart language.
Constructors in Dart
A constructor is a class member function in dart language that has same name class itself. Constructors does not inherited by sub class.
Example of constructor
class Construct{
Construct.MyConstruct(){
print("Wecome in Dart Constructor !");
}
Construct.MyConstruct1(String s){
print("Wecome in Parametrized Constructor !");
}
}
void main()
{
Construct obj = new Construct.MyConstruct();
Construct obj1 = new Construct.MyConstruct1("Dart");
}
|
Output:

Constructor are different types
- Default constructor
The default constructor is also know as no argument constructor, if you do not declare a default constructor, it is automatically created.
Example of default constructor
class DefaulConstruct{
DefaulConstruct() {
print("I am a Default Constructor");}
}
void main() {
DefaulConstruct obj = new DefaulConstruct();
}
|
Output:

-
Named constructor
You can used named constructor to implement multiple constructor for a class.
-
Factory constructor
factory constructor is used, when we want to create a instance only once; and use this instance for multiple time.
Example of constant constructor
class constcon{
final int a;
const constcon(this.a);
}
main(){
var a = const constcon(1);
var b= const constcon(1);
print("The value of with const constructor is ${a==b}");
/********And if you check without const **************/
var c = new constcon(1);
var d = new constcon(2);
print("The value of WithOut const constructor is ${c==d}");
}
|
Output:

Got a programming related question? You may want to post your question here