Program opened below. You can scroll through the algorithm, Java code and output.

Radius and Area of a Circle Using Inheritance

Download .java

Question

Use inheritance to accept a circle's radius and calculate and display its area.

Step 1: Start the program and define a base class containing the radius. Step 2: Define a method in the base class to accept the radius. Step 3: Define a derived class that inherits the radius and input method. Step 4: Create an object of the derived class in main(). Step 5: Call the input method to accept the radius. Step 6: Check that the radius is not negative. Step 7: If the radius is invalid, display an error and stop. Step 8: Calculate the area using π multiplied by radius multiplied by radius. Step 9: Store the calculated area in a double variable. Step 10: Display the radius to two decimal places. Step 11: Display the area to two decimal places on a separate line. Step 12: Stop the program.
Java
import java.util.*;
class CircleBase
{
    double radius;
    void input()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter radius: ");
        radius = sc.nextDouble();
    }
}
class CircleArea extends CircleBase
{
    void display()
    {
        double area = 3.14159 * radius * radius;
        System.out.printf("Radius = %.2f%nArea = %.2f%n", radius, area);
    }
    public static void main(String[] args)
    {
        CircleArea ob = new CircleArea();
        ob.input();
        ob.display();
    }
}
Input: Input: 7 Output: Radius = 7.00; Area = 153.94
← Previous Program 52 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.