a) Create a class named ‘Rectangle’ with two data members- length and breadth and a method to calculate the area which is ‘length*breadth’. The class has three constructors which are :
1 – having no parameter – values of both length and breadth are assigned zero.
2 – having two numbers as parameters – the two numbers are assigned as length and breadth respectively.
3 – having one number as parameter – both length and breadth are assigned that number.
Now, create objects of the ‘Rectangle’ class having none, one and two parameters and print their areas.
public class Rectangle
{
int length;
int breadth;
public Rectangle()
{
length=0;
breadth=0;
}
public Rectangle(int l, int b)
{
length=l;
breadth=b;
}
public Rectangle(int n)
{
length=n;
breadth=n;
}
public void calculate()
{
System.out.println("area = "+ (length*breadth));
}
public static void main()
{
Rectangle R1 = new Rectangle();
Rectangle R2 = new Rectangle(10,5);
Rectangle R3 = new Rectangle(6);
R1.calculate();
R2.calculate();
R3.calculate();
}
}
b) Differentiate a constructor and function
Constructor is used to initialize an object whereas method is used to exhibits functionality of an object.
Constructors are invoked implicitly whereas methods are invoked explicitly.
Constructor does not return any value where the method may/may not return a value.
In case constructor is not present, a default constructor is provided by java compiler. In the case of a method, no default method is provided.
Constructor should be of the same name as that of class. Method name should not be of the same name as that of class.