Create a class named 'Rectangle' with two data members- length and breadth and a method to claculate 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.
Answers
Answer:
see this pic
Hope it helps
Create a class named 'Rectangle' with two data members- length and breadth and a method to calculate the area which is 'length*breadth'.
Explanation:
Java Constructors Program
class Rectangle{
private int length;
private int width;
Rectangle(){
this.length=0; // assuming default length=0
this.width=0; // assuming default width=0
}
Rectangle(int length, int width){
this.length=length;
this.width=width;
}Rectangle(int length){
this.length=length;
this.width=length;
}
int area(){
return length*width;
}
}
public class Main{
public static void main(String args[]){
Rectangle r1= new Rectangle();
System.out.println("Area of r1: "+ r1.area());
Rectangle r2= new Rectangle(20,30);
System.out.println("Area of r2: "+ r2.area());
Rectangle r3= new Rectangle(10);
System.out.println("Area of r3: "+ r3.area());
}
}
Output
Area of r1: 0
Area of r2: 600
Area of r3: 100