Create an abstract class “Shape” with abstract methods “getArea()” and “getPerimeter()”. Implement two subclasses “Rectangle” and “Circle” which extend “Shape” and implement the abstract methods. Create a “Square” class which extends “Rectangle” and overrides the necessary methods. Create objects of all classes and test their behavior.
Solution:
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
public double getArea() {
return super.getArea();
}
public double getPerimeter() {
return super.getPerimeter();
}
}
And here’s an example of how you can use these classes into main class:
public class AbstractExample {
public static void main(String[] args) {
Shape rectangle = new Rectangle(4, 6);
Shape circle = new Circle(3);
Shape square = new Square(5);
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
System.out.println("Square area: " + square.getArea());
System.out.println("Square perimeter: " + square.getPerimeter());
}
}
Save the above Program with “AbstractExample .Java” then compile it with the following command :
javac AbstractExample.java //to compile the code java AbstractExample //to run the code
Output is :
Rectangle area: 24.0 Rectangle perimeter: 20.0 Circle area: 28.274333882308138 Circle perimeter: 18.84955592153876 Square area: 25.0 Square perimeter: 20.0
Want to practice more problems involving Abstract Classes? Click here.