What is a default constructor

A default constructor is a special type of a constructor which takes no arguments. It is a called a default constructor because if the programmer does not create a constructor in the class then the default constructor gets created automatically. This is because you need at least one constructor to create the object of a class and in the absence of any other constructor the default constructor helps in the object creation.

Look at the code below

// class defintion  class Test  {  }    // Creating object of the Test class  Test t = new Test();

You see that we have kept the Test class empty and have not created any constructor. When we are creating the object we write new Test(); Here Test() is the default constructor which we are using to create the object. You can easily see that this default constructor got added to the class automatically.

Can the programmer create his own default constructor?

The answer is yes. The rule followed is simple – If the programmer does not create any constructor in the class then the default constructor gets created automatically. But if the programmer adds at least one constructor to the class then the default constructor is not created automatically.

How to create a default constructor?

Adding a default constructor to your class is easy. You just need to create a function with the same name as that of the class, no return type and no arguments. Look at the code below

class Test  {      // Default constructor created by the programmer      public Test()      {          // Write your own code here.      }  }

Now create the object of the Test class by writing this code

Test t = new Test(); // During execution your default constructor will be called.

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp