Category Archives: Constructor

Default & Parameterized constructor :

The default constructor are used to initialize the object variables with some default values at the time of object instantiation. Which constructor has arguments thats called Parameterized Constructor.  

<br />class Rectangle {
int length;
int breadth;
Rectangle() //Default constructor

{
length = 0;
breadth = 0;
}
Rectangle(int len,int bre) // Parameterized constructor
{
length = len;
breadth = bre;
}
void rectArea()
{
int result;
result = length * breadth ;
System.out.println("The area of the rectangle is : " + result );
}
}
class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle(); //calling default constructor
Rectangle r2 = new Rectangle(5,10); // calling parameterized constructor

r1.rectArea();
r2.rectArea();

}
}

Output :-
java1

Constructor Declaration :

A constructor is a special type of method that enables an object to initialize itself when it is created. Constructors have the same name as the class itself and they do not specify a return type.

class Sum
{
int first;
int second;
}
Sum (int x, int y) // Constructor method
{
first = x ;
second = y ;
}
int result()
{
return ( first + second );
}
}