In: Computer Science
The following points can be followed to create the mentioned four classes:
The java program:
import java.lang.Math.*;
import java.text.DecimalFormat;
//abstract class Shape2D
abstract class Shape2D{
abstract double get2DArea();
}
//class Retangle2D
class Retangle2D extends Shape2D{
//data members
private double length;
private double width;
//constructor
Retangle2D(double l,double w){
length = l;
width = w;
}
//method to get area
public double get2DArea(){
return length * width;
}
}
//class Circle2D
class Circle2D extends Shape2D{
//date member
private double radius;
//constructor
Circle2D(double r){
radius = r;
}
//method to get area
public double get2DArea(){
return Math.PI * radius * radius;
}
}
public class Shape2DDriver
{
public static void main(String[] args) {
//Object of Circle2D
Circle2D c = new Circle2D(6);
//Object of Retangle2D
Retangle2D r = new Retangle2D(11,8);
//area of Circle
displayName(c);
//area of Retangle
displayName(r);
//using abstract class
Shape2D s = new Retangle2D(7,5);
displayName(s);
}
//method displayName
static void displayName(Shape2D obj){
//format to round upto one decimal
DecimalFormat df = new DecimalFormat("#.#");
//print the Area of the object
System.out.println("Area :" + df.format(obj.get2DArea()) );
}
}
Sample output: