In: Computer Science
package abstracts;
// Defines an abstract class Shapes2D
abstract class Shapes2D
{
// Declares an abstract method to return area of 2D
shape
abstract double get2DArea();
}// End of abstract class Shapes2D
// Defines a sub class Rectangle2D extended from super class
Shapes2D
class Rectangle2D extends Shapes2D
{
// Instance variable to store length and width
double length;
double width;
// Parameterized constructor to assign parameter
values to instance variables
Rectangle2D(double le, double wi)
{
length = le;
width = wi;
}
// Overrides method to return area of rectangle
public double get2DArea()
{
return length * width;
}
}// End of class Rectangle2D
// Defines a sub class Circle2D extended from super class
Shapes2D
class Circle2D extends Shapes2D
{
// Instance variable to store radius
double radius;
double width;
// Parameterized constructor to assign parameter value
to instance variable
Circle2D(double ra)
{
radius = ra;
}
// Overrides method to return area of circle
public double get2DArea()
{
return 3.141 * radius *
radius;
}
}// End of class Circle2D
// Driver class definition
public class Shape2DDriver
{
// Defines a method to receive Shapes2D class
object
static void displayName(Shapes2D object)
{
// Checks if parameter object is an
instance of Rectangle2D class
if(object instanceof
Rectangle2D)
// Calls the
method to calculate and return the area of rectangle
System.out.printf("\n Rectangle Area: %.2f",
object.get2DArea());
// Otherwise checks if parameter
object is an instance of Circle2D class
else if(object instanceof
Circle2D)
// Calls the
method to calculate and return the area of circle
System.out.printf("\n Circle Area: %.2f",
object.get2DArea());
}
// main method definition
public static void main(String []s)
{
Shapes2D object[] = new
Shapes2D[2];
object[0] = new
Circle2D(12.2);
object[1] = new Rectangle2D(5.0,
5.0);
displayName(object[0]);
displayName(object[1]);
}
}// End of driver class
Sample Output:
Circle Area: 467.51
Rectangle Area: 25.00