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 :-
- Default constructor
- Parameterized constructor
- 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); "
- In statement :- " rectangle r2= new rectangle(); "
- When there is no constructor , JAVA call implicit constructor which set all instance variable to zero.
No comments:
Post a Comment