In: Computer Science
// Shape2D.java
public abstract class Shape2D
{
public abstract double get2DArea();
}
//end of Shape2D.java
// Rectangle2D.java
public class Rectangle2D extends Shape2D
{
// fields
private double length;
private double width;
// constructor
public Rectangle2D(double length, double width)
{
this.length = length;
this.width = width;
}
// overriden method to return the area of rectangle
@Override
public double get2DArea() {
return length*width;
}
}
//end of Rectangle2D.java
// Circle2D.java
public class Circle2D extends Shape2D
{
// field
private double radius;
// constructor
public Circle2D(double radius)
{
this.radius = radius;
}
// overriden method to return the area of circle
@Override
public double get2DArea() {
return Math.PI*Math.pow(radius, 2);
}
}
//end of Circle2D.java
// Shape2DDriver.java
public class Shape2DDriver {
// method that takes as input Shape2D object and displays the
area of the object, rounded to one decimal place.
public static void displayName(Shape2D shape)
{
System.out.printf("Area: %.2f\n",shape.get2DArea());
}
public static void main(String[] args)
{
// test the class and methods
Shape2D shape = new Rectangle2D(12, 7);
displayName(shape);
shape = new Circle2D(5);
displayName(shape);
}
}
//end of Shape2DDriver.java
Output :
I have tried to explain it in very simple language and I hope that i have answered your question satisfactorily.Leave doubts in comment section if any.