Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 11

5 marks

Computer ScienceISC 2020 Computer Science Paper 1ProgramInheritance, Interfaces and Polymorphism

Write the program described below.

An interface Data is defined with a data member and a method volume( ) which returns the volume of…

An interface Data is defined with a data member and a method volume( ) which returns the volume of the implementing shape. A super class Base has been defined to contain the radius of a geometrical shape. Define a sub class CalVol which uses the properties of the interface Data and the class Base and calculates the volume of a cylinder. The details of the members of the interface and both the classes are given below: Interface name : Data Data member: double pi : initialize pi = 3.142 Member functions/methods: double volume( ) Class name: Base Data member/instance variable: rad : to store the radius in decimal Member functions/methods: Base(…) : parameterized constructor to initialize the data member void show( ) : displays the radius with an appropriate message Class name: CalVol Data member/instance variable: ht : to store the height in decimal Member functions/methods: CalVol(…) : parameterized constructor to initialize the data members of both the classes double volume( ) : calculates the volume of a sphere by using the formula ( pi x radius2 x height ) void show( ) : displays the data members of both the classes and the volume of the sphere with appropriate message Assume that the interface Data and the super class Base has been defined. Using the concept of inheritance, specify the class CalVol giving the details of the constructor(…), double volume( ) and void show( ). The interface, super class, main function and algorithm need NOT be written.

Answer

Answer

class CalVol extends Base implements Data
{
    double ht;

    CalVol(double r, double h)
    {
        super(r);
        ht = h;
    }

    public double volume()
    {
        return pi * rad * rad * ht;
    }

    void show()
    {
        super.show();
        System.out.println("Height = " + ht);
        System.out.println("Volume of the cylinder = " + volume());
    }
}
Explanation: CalVol extends the class Base (to reuse rad and show()) and implements the interface Data (so it must define volume(), which has to be public, and can use the constant pi = 3.142). The constructor passes the radius to the super class constructor with super(r) and stores the height. volume() returns pi x rad x rad x ht, the volume of a cylinder. show() calls super.show() to display the radius, then displays the height and the volume. Note: the question's stem says cylinder while the method description says sphere; the given formula pi x radius^2 x height is that of a cylinder. Tested with stub Base and Data classes: for radius 3.5 and height 10 the volume printed is 384.895.