Write a java program to create an abstract class named Shape that contains two integers and an empty method named print Area (). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape
CODE:
abstract class Shape {
protected int dimension1;
protected int dimension2;
public Shape(int dimension1, int dimension2) {
this.dimension1 = dimension1;
this.dimension2 = dimension2;
}
public abstract void printArea();
}
class Rectangle extends Shape {
public Rectangle(int length, int width) {
super(length, width);
}
@Override
public void printArea() {
System.out.println("Area of Rectangle: " + (dimension1 * dimension2));
}
}
class Triangle extends Shape {
public Triangle(int base, int height) {
super(base, height);
}
@Override
public void printArea() {
System.out.println("Area of Triangle: " + (0.5 * dimension1 * dimension2));
}
}
class Circle extends Shape {
public Circle(int radius) {
super(radius, radius);
}
@Override
public void printArea() {
System.out.println("Area of Circle: " + (Math.PI * dimension1 * dimension2));
}
}
public class ShapeTest {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
Triangle triangle = new Triangle(6, 8);
Circle circle = new Circle(3);
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}
- Define an abstract class Shape with two protected instance variables dimension1 and dimension2.
- Define a constructor in the Shape class to initialize these variables.
- Define an abstract method printArea() in the Shape class.
- Define three subclasses Rectangle, Triangle, and Circle, each extending the Shape class.
- Each subclass has its own constructor to initialize the dimensions inherited from the Shape class.
- Each subclass overrides the printArea() method to calculate and print the area of the respective shape.
- Define a class ShapeTest.
- Inside the ShapeTest class: a. Create objects of Rectangle, Triangle, and Circle. b. Call the printArea() method for each object to print the area of the respective shape.
- End of the program.