Java program that calculates the area of a cylinder and a circle using the super
keyword:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import java.util.*; class Shape { double radius; Shape(double r) { radius = r; } double area() { return 0.0; } } class Circle extends Shape { Circle(double r) { super(r); } double area() { return Math.PI * radius * radius; } } class Cylinder extends Shape { double height; Cylinder(double r, double h) { super(r); height = h; } double area() { return 2 * Math.PI * radius * height + 2 * Math.PI * radius * radius; } } class Test { public static void main(String args[]) { Circle c = new Circle(10); System.out.println("Area of circle is: " + c.area()); Cylinder cy = new Cylinder(10, 20); System.out.println("Area of cylinder is: " + cy.area()); } } |
In this program, the Shape
class is the base class with a single instance variable radius
. The Circle
class extends Shape
and provides its own implementation of the area
method to calculate the area of a circle. The Cylinder
class extends Shape
as well and adds an additional instance variable height
. It also provides its own implementation of the area
method to calculate the surface area of a cylinder.
In the main
method of the Test
class, objects of both the Circle
and Cylinder
classes are created and their areas are calculated using the area
method. The result is printed to the screen. The super
keyword is used in the constructors of both the Circle
and Cylinder
classes to call the constructor of the parent Shape
class and initialize the radius
instance variable.