‹ Back to the paper
Question 10
5 marks
Computer ScienceISC 2020 Specimen Computer Science Paper 1ProgramInheritance, Interfaces and Polymorphism
Write the program described below.
An interface Shape is defined with a method area() which returns the area of the implementing…
An interface Shape is defined with a method area() which returns the area of the implementing shape.
Create the classes Circle and Rectangle which implement the interface Shape. These classes have attributes which reflect their dimensions (radius for a circle, height and width for a rectangle) which are set by their constructors.
The details of the members of the interface and both the classes are given below:
Interface name : Shape
Member functions/methods:
double area() : returns the area of the implementing shape
Class name : Circle
Data members/instance variables:
radius : to store radius of the circle in decimal
Member functions/methods:
Circle(int r) : parameterized constructor to initiallize radius=r
double area() : to calculate area of the circle [ area of a circle is $3.14 * radius * radius$ ]
Class name : Rectangle
Data members/instance variables:
length : to store length of the rectangle in decimal
breadth : to store breadth of the rectangle in decimal
Member functions / methods:
Rectangle(int l, int b) : parameterized constructor to initialize length=l, breadth=b
double area() : to calculate area of the rectangle [ area of a rectangle is $length * breadth$ ]
Assume that the Interface Shape has been defined. Using the concept of inheritance, specify the classes Circle and Rectangle giving details of their constructors and double area() respectively.
The interface, main function and algorithm need NOT be written.
Answer
Answer
class Circle implements Shape
{
double radius;
Circle(int r)
{
radius = r;
}
public double area()
{
return 3.14 * radius * radius;
}
}
class Rectangle implements Shape
{
double length, breadth;
Rectangle(int l, int b)
{
length = l;
breadth = b;
}
public double area()
{
return length * breadth;
}
}Explanation: Both classes implement the interface Shape (the keyword implements is used for an interface), so each must define the method area(), which must be declared public as interface methods are public. The constructor of Circle stores the radius and area() returns 3.14 x radius x radius. The constructor of Rectangle stores the length and breadth and area() returns length x breadth. Tested with an interface Shape { double area(); }: Circle(7).area() gives 153.86 and Rectangle(5, 4).area() gives 20.0.