Dart: Constructor | Default Constructor | Parameterized Constructor

Dart: Constructor | Default Constructor | Parameterized Constructor

ยท

2 min read

  • we can use constructor while creating object.

  • Constructor name always the similar to class while method's name we can write according to our preference.

  • As we know there are many element is class , and out of all the element the Constructor will run the first among the all element.

  • If there are no element in class than we can say this constructor as default constructor.

  • Creation of constructor as same as the method there is only one difference that we can not get any return value to constructor and the name always the same as the class.

  • The default constructor has no any argument. Apart form that if you do not define constructor then default constructor provided for you.

  • Let's see with one example.

    Here , you can see that we did not call the method in the main function , still we got the output of our program without any error.

  • In constructor we do not need to call the in main method it's by default call with the object.


//Default Constructor 
void main()
{
  var addition = sum();
}

class sum
{
   sum()
   {

    print("Hello! This is Default Constructor ");
   }
}

  • If we pass Parameter in Constructor than it's called Parameterised Constructor.

//Parameterised Constructor 
void main()
{
  var addition = sum(10,20);
}

class sum
{
   sum(int a , int b)
   {
    int c =a +b;
    print("The sum of a + b = $c");
   }
}

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย