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.
Circle2D 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.
Written in java
HERE IS THE CODE AS PER YOUR REQUIREMENT
CODE:
// creating abstract class
public abstract class Shape2D{
// creating abstract method
public abstract double get2DArea();
}
// creating rectangle2D class that inherits shape2D
class Rectangle2D extends Shape2D{
double length;
double width;
// constructor that takes double inputs
Rectangle2D(double length, double width){
this.length = length;
this.width = width;
}
// returns the rectangle length
public double get2DArea(){
return length*width;
}
}
// creating the circle2D class that inherits Shape2D
class Circle2D extends Shape2D{
double radius;
// constructor that takes double input
Circle2D(double radius){
this.radius = radius;
}
// returns circle length
public double get2DArea(){
return Math.PI*radius*radius;
}
}
// Driver class to test and execute
class Shape2DDriver{
// displayname method to display the area of the
objects we created
public static void displayName(Shape2D nShape){
System.out.println("Area :
"+Math.round(nShape.get2DArea()));
}
public static void main(String[] args) {
Shape2D rectangle = new
Rectangle2D(5.5,2.5);
Shape2D circle = new
Circle2D(2.5);
displayName(rectangle);
displayName(circle);
}
}
SCREENSHOTS:
OUTPUT:
NOTE: Be sure save java file name with Shape2D.java
IF YOU HAVE ANY QUERIES FEEL FREE TO ASK AT COMMENTS
PLEASE DO LIKE :)
Get Answers For Free
Most questions answered within 1 hours.