why we need construtor?


why we need construtor?

Each and every time after object creation we have to initialize the variable manully byusing the method passing variable.Find the example below.

Class box
{
double width;
double height; //instance variable
double volume ()
{
return width*height;
}
void meth()
{
width=a;
height=b; // initialize the variable
}
}
class MainBox
{
public static void main(String args[])
{
Box my=new Box();
my.meth(10,20);
}
}


For avoiding these complexity we go for constructor.Find Below Example
Class box
{
double width;
double height; //instance variable

box()
{
width=10;
height=20;
}
double volume ()
{
return width*height;
}
}
class MainBox
{
public static void main(String args[])
{
Box my=new Box();
System.out.println(my.volume());
}
}

No comments:

Post a Comment

Loading