Java Constructors

The constructor is a set of statements which starts with open curly braces “{“ and ends with close curly braces “ } “ and similar to the method but the name of the constructor is same as the name of a class.

resides is automatically called immediately after the object of that class created in which it resides.

A class can contain more than one constructor.  If a class does The constructor the constructor, the system provides the default constructor which is known as system default constructor resides.

The default constructor  automatically initialize all instance variable to zero

Characteristics of Constructor

  • The constructor has the same name as the class in which it resides.                        
  • The constructor is automatically called immediately after the object of that class created in which it resides.
  • Constructor neither returns value nor void.                                                                             
  • The constructor can be overloaded.                                                                                                              
  • The constructor without argument is called as default constructor.                                                           
  • Default constructor automatically initialize all instance variable to zero  

Constructor With Arguments

In Java, we can create a create a constructor which can take zero, one or more than arguments.

Result

Note: In the above program we have created class Student and three constructors  Student(), Student(long r) and Student(long r, String n ).

When the line “ Student   obj1  =  new   Student(); ” executes and immediately after the object “obj1” is create, Student() constructor will be called.

When The constructor line “ Student    obj2  =  new  Student (1); ” executes and immediately after the object “obj2” is create, Student(long r) constructor will be called and passes the value 1 to the constructor.

When line “ Student    obj3  =  new  Student(1,”Ram”); ” executes  and immediately after the object “obj3” is create, Student(long r, String n) constructor will be called and passes the value 1 and “Ram” to the constructor.