Saturday 26 October 2013

CONSTRUCTOR

A constructor is used to create object through new operator.

Program :-
class Rectangle
{
double width;
double height;
Rectangle()
{
System.out.println("constructing Rectangle");
width=10;
height=20;
}
double area()
{
return width*height;
}
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle rec=new rectangle();
double area;
area=rec.area();
System.out.println("area is"+area);
}
}

Output :-
constructing Rectangle
area is 200

Note :- In above program line written with blue line is code for creating constructor...i.e
Rectangle()
{
System.out.println("constructing Rectangle");
width=10;
height=20;
}

No comments:

Post a Comment