KnowledgeBoat Logo
|

Computer Science

What is the need of an Abstract Class? Explain.

Objects & Classes

2 Likes

Answer

Let's say I have a class called Shape that I want to use as the base class for different shapes like Circle, Rectangle, etc. I have a method in Shape class named computeArea that calculates the area of its corresponding shape. I cannot give any definition of computeArea method in Shape class as each shape computes its area in a different way but I want to enforce that any class deriving from Shape class implements computeArea method to calculate its area. To do this, I will make Shape class as abstract class and computeArea method as abstract method. Here is the complete program to show this usage of abstract Shape class.

/*
 * Abstract Shape Class Definition
 */
public abstract class Shape
{
    public abstract double computeArea();
}

/*
 * Circle derives from Shape and 
 * implements computeArea method
 */
public class Circle extends Shape
{ 
    private double radius;
    
    public Circle(double r) {
        radius = r;
    }
    
    public double computeArea() {
        double area = 3.14159 * radius * radius;
        return area;
    }
}

/*
 * Rectangle derives from Shape and 
 * implements computeArea method
 */
public class Rectangle extends Shape
{
    private double length;
    private double width;
    
    public Rectangle(double l, double w) {
        length = l;
        width = w;
    }
    
    public double computeArea() {
        double area = length * width;
        return area;
    }
}

/*
 * Test Class with main method to
 * instantiate objects of Rectangle
 * and Circle and display their area
 */
public class TestShape
{
    public static void printArea(Shape s) {
        double area = s.computeArea();
        System.out.println("Area of shape = " + area);
    }
    
    public static void main(String args[]) {
        Rectangle r = new Rectangle(6.0, 3.0);
        Circle c = new Circle(5.0);
        printArea(r);
        printArea(c);
    }
}

Answered By

1 Like


Related Questions