Sunday, 6 January 2013

CONSTRUCTORS IN JAVA

CONSTRUCTORS
Constructors define what occur or should be done when object is created. It can be used for automatic initialization.
               Constructor have same name as of class name and syntactically similer to a method. After defining constructor is called immediately automatically after creating of object before job of new operator is done.
                        Constructor have no return type even "void" , because implicit return type constructor is class type in which it reside. Constructor can be of three types :-
  1. Default constructor
  2. Parameterized constructor
  3. Overloading Constructor

 NOW we take a example to define constructor more precisely :-
consider the given JAVA program :-
                              /*start program*/
                              class rectangle 
                                  {
                               int len;
                               int bre;
                               //default constructor start
                               rectangle()
                               {
                                 len=10;
                                 bre=10;
                                }                              
                              //Parametrized constructor start
                                 rectangle(int x, int y)
                                 {
                                   len=x; 
                                   bre=y;
                                   }

                                   }                //rectangle class end here;

                               class constructor_demo {
                               Public static void main(String s[])
                               {
                                  rectangle r1 = new rectangle(5,10);
                                   rectangle r2 = new rectangle();
              
                                 }
                                  }
                              /*end of program*/  

  • In this program we use two constructor . One of them is default constructor and other is parametrized constructor  which takes parameter list. Since there are two constructor with same name so they are overloaded constructor also.
  • In statement :- "rectangle r1= new rectangle(5,10); "
is execute it immediately call constructor. Since we pass argument so parameterized constructor is called and initialize object.  It sets length to 5 and bredth to 10;
 
  • In statement :- " rectangle r2= new rectangle(); "
on execution lead to call default construtor. This will set length to 10 and breadth to 10.
 
  • When there is no constructor , JAVA call implicit constructor which set all instance variable to zero.          

No comments:

Post a Comment