In: Computer Science
Shapes2D
Write the following four classes to practice using an abstract class and polymorphism. Submit all four classes.
Shape2D class
For this class, include just an abstract method name get2DArea() that returns a double.
Rectangle2D class
Make this class inherit from the Shape2D class. Have it store a length and a width as fields. Provide a constructor that takes two double arguments and uses them to set the fields. Note, the area of a rectangle is the length times the width.
Rectangle2D class
Also make this class inherit from the Shape2D class. Have it store a radius as a field. Provide a constructor that takes a double argument and uses it to set the field. Note, the area of a circle is PI times it's radius times it's radius.
Shape2DDriver class
Have this class provide a method named displayName() that takes an object from just any of the above three classes (you can't use an Object type parameter). Have the method display the area of the object, rounded to one decimal place.
Code
abstract class Shape2D
{
abstract double get2DArea();
}
class Rectangle2D extends Shape2D
{
private double length,width;
public Rectangle2D(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double get2DArea() {
return width*length;
}
}
class Circle2D extends Shape2D
{
private double radius;
public Circle2D(double radius) {
this.radius = radius;
}
@Override
double get2DArea() {
return Math.PI*radius*radius;
}
}
public class Shape2DDriver {
public static void main(String[] args) {
Rectangle2D r1=new Rectangle2D(10, 20);
Circle2D c1=new Circle2D(100);
System.out.print("Area of the Rectangle is: " );
displayName(r1);
System.out.print("Area of the Circle is: " );
displayName(c1);
}
public static void displayName(Shape2D obj)
{
System.out.printf("%.2f%n",obj.get2DArea());
}
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.