Constructors
Constructors
Objects that are created must be given initial values. The first approach uses the dot operator to access the instance variables and then assign values to them individually. It would be too lengthy to initialize all the variables of all the objects.
The second approach is to take the help of a method like getdata to initialize each object individually using the statements like
Rect1.getdata(15,10);
Constructor enables an object to initialize itself when it is created. Constructors have the same name as the class itself. Constructor do not specify return type, not even void. This is because they return instance of the class itself.
Let us consider the example to illustrate constructor.
Class rectangle
{
Int length;
Int width;
Rectangle(intx, int y ) // constructor method
{
Length = x;
Width = y;
}
Intrextarea()
{
Return(length x width );
}
}
Class rectanglearea
{
Public static void main(string args[]);
{
Rectangle rect1 = new rectangle(15,10); // calling constructor
Int area1 = rect1.rectarea();
System.out.println(“Area = “ +area1);
}
}