Test2 2022
Test2 2022
Design a Java application that uses method overriding. Create a superclass called Circle.
This class defines methods called getRadius(), getColor() and getArea(). It also contains
two private instance variables: radius (of type double) and color (of type String), with
default values 1.0 and “red”, respectively. The superclass must have two overloaded
constructors: 1) constructor which sets both radius and color to default; 2) constructor
with given radius and color.
Create classes for different geometrical shapes called Cylinder, Cone and Torus. These
classes must contain two constructors each, – one with default values and another one
with given values. Use the following inheritance structure:
Create the driver class containing the main() method and call it TestShapes. The
application must produce an output similar to the given on the next page (calculations
done with default and given values, respectively).
i
Circle: radius = 1.00000; colour = red; area = 3.14159
Circle: radius = 12.0000; color = blue; area = 452.389;
Torus: radius = 1.00000; colour = red; main radius = 1.00000; volume = 19.7392;
surface area = 39.4784
Torus: radius = 10.0000; colour = orange; main radius = 20.0000;
volume = 39478.4; surface area = 7895.68
ii
Model answer
6 // first constructor
7 public Circle () {
8 radius = 1.0;
9 color = " red " ;
10 }
11
12 // second constructor
13 public Circle ( double r , String c ) {
14 radius = r ;
15 color = c ;
16 }
17
Subclass Cylinder:
1
iii
16
17 // retrieve height
18 public double getHeight () {
19 return height ;
20 }
21 // calculate the volume
22 public double getVolume () {
23 return getArea () * height ;
24 } }
Subclass Cone:
1
Subclass Torus:
1 public class Torus extends Circle {
2 private double torusMainRadius ;
3 // constructor with default values but given height
4 public Torus () {
5 super () ;
6 torusMainRadius = 1.0;
7 }
8 // constructor with given values
9 public Torus ( double radius , String color , double mr ) {
10 super ( radius , color ) ;
11 torusMainRadius = mr ;
12 }
13
iv
20 return getArea () * 2.0 * Math . PI * getMainRadius () ;
21 }
22 public double getSurfaceArea () {
23 return 4.0 * Math . PI * Math . PI * getRadius () * getMainRadius () ;
24 } }
v
42 t1 . getVolume () , t1 . getSurfaceArea () ) ;
43
Output:
Torus: radius = 1.00000; colour = red; main radius = 1.00000; volume = 19.7392;
surface area = 39.4784
Torus: radius = 10.0000; colour = orange; main radius = 20.0000;
volume = 39478.4; surface area = 7895.68
vi