PRASHNIKAप्रश्निका
Back to the paper

A super class Circle has been defined to calculate the area of a circle. Define a subclass Volume…

Computer Science20245 marksProgram
A super class Circle has been defined to calculate the area of a circle. Define a subclass Volume to calculate the volume of a cylinder. The details of the members of both the classes are given below: Class name : Circle Data members/instance variables: radius : to store the radius in decimals area : to store the area of a circle Methods / Member functions: Circle( ... ) : parameterized constructor to assign values to the data members void cal_area() : calculates the area of a circle ($\pi r^2$) void display( ) : to display the area of the circle Class name : Volume Data members/instance variables: height : to store the height of the cylinder in decimals volume : to store the volume of the cylinder in decimals Methods / Member functions: Volume( ... ) : parameterized constructor to assign values to the data members of both the classes double calculate( ) : to calculate and return the volume of the cylinder using the formula ($\pi r^2 h$) where, r is the radius and h is the height void display( ) : to display the area of a circle and volume of a cylinder Assume that the super class Circle has been defined. Using the concept of inheritance, specify the class Volume giving the details of the constructor(...), double calculate( ) and void display( ). The super class, main function and algorithm need NOT be written.

Answer

Answer

AI
class Volume extends Circle
{
    double height, volume;

    Volume(double r, double h)
    {
        super(r);
        height = h;
    }

    double calculate()
    {
        cal_area();
        volume = area * height;
        return volume;
    }

    void display()
    {
        super.display();
        System.out.println("Volume of Cylinder = " + volume);
    }
}
Explanation: The parameterised constructor Volume(r,h) passes the radius up to the superclass Circle's constructor using super(r), and stores height in the subclass. calculate() invokes the inherited cal_area() (which computes and stores area = pi * radius^2 in the superclass), then multiplies this area by height to get the volume of the cylinder (pi * r^2 * h), storing it in volume and returning it. display() calls super.display() to reuse the superclass's printing of the area, then prints the volume, demonstrating inheritance (reusing radius/area/cal_area from Circle) and method overriding of display(). Tested (run for real) with a stub Circle class matching the given specification: for radius=3, height=5, the program correctly computed area = 28.274... and volume = 141.371...
Inheritance, Interfaces and Polymorphism

From ISC 2024 Specimen Computer Science Paper 1, question 10.