Write a program to create a class Rectangle with the following information:
length, breadth in integer.
• Add two constructors, (a) default constructor, and (b) constructor to pass on length
and breadth of a Rectangle.
• Add a method printData( ) to print the two information about the rectangle in
console.
• Add methods printArea( ) and printPerimeter( ) to compute and print the area and
perimeter of rectangle in console.
• Create two objects of this class, r1 and r2. Show the output of both the constructors
and all method of these two objects
public class Rectangle {
private int length;
private int breadth;
public Rectangle() {
length = 0;
breadth = 0;
}
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public void printData() {
System.out.println("Length: " + length + ", Breadth: " + breadth);
}
public void printArea() {
System.out.println("Area: " + length * breadth);
}
public void printPerimeter() {
System.out.println("Perimeter: " + 2 * (length + breadth));
}
}
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.printData();
r1.printArea();
r1.printPerimeter();
Rectangle r2 = new Rectangle(10, 5);
r2.printData();
r2.printArea();
r2.printPerimeter();
}
}
Comments
Leave a comment