Create a class named 'Rectangle' with two datamembers 'length' and 'breadth' andtwo methods to print the area and perimeter of the rectangle respectively. Its constructorhaving parameters for length and breadth is used to initialize length and breadth of therectangle. Let class 'Square' inherit the 'Rectangle' class with its constructor having a
parameter for its side (suppose s) calling the constructor of its parent class as'super(s,s)'. Print the area and perimeter of a rectangle and a square.
public class Rectangle {
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public void area() {
System.out.println(breadth * length);
}
public void perimeter() {
System.out.println(2 * (breadth + length));
}
}
public class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 5);
Rectangle square = new Square(10);
rectangle.area();
rectangle.perimeter();
System.out.println();
square.area();
square.perimeter();
}
}
Comments
Leave a comment