Ad

Inheritance

                                 Inheritance

Task 1:
Make a class Circle that has two private attribute color and radius. Create a fully parameterized constructor. This class has a method calculateArea(), which calculates area of circle.
Make a class Cylinder that has one private attribute height. Here Cylinder is a Circle. Create a fully parameterized constructor. This class has a method calculateVolume(), which calculates volume of cylinder.
In test class, create an object of cylinder. Ask user to input value of color, radius and height. Print color, radius, and area of circle and volume of cylinder.


Solution:

//Circle Class:

/**
 *
 * @author usman
 */
 class Circle {
    private String color;
    private double radius;

    public Circle(String color, double radius) {
        this.color = color;
        this.radius = radius;
    }

    public String getColor() {
        return color;
    }
    
    
    public double getRadius()
    {
        return radius;
    }
    
    //Calculate Method
    public double calculateArea(double radius)
    {
        double a = 3.14*radius*radius;
        return a;
       
    }
    
}

//Cylinder Class:

/**
 *
 * @author usman
 */
 class Cylinder extends Circle {
    private double height;

    public Cylinder(double height, String color, double radius) {
        super(color, radius);
        this.height = height;
    }

    public double getHeight() {
        return height;
    }
    public double calculateVolume(double radius,double height)
    {
        double volume = 3.14*getRadius()*getRadius()*height;
        return volume;
    }
    
}


//Test Class:

/**
 *
 * @author hashmi
 */
import java.util.*;
public class TestClass {
    public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       
        
        System.out.println("Enter the color: ");
        String color = input.nextLine();
        System.out.println("Enter the radius: ");
        double radius = input.nextDouble();
        System.out.println("Enter the height: ");
        double height = input.nextDouble();
        
         Cylinder obj1 = new Cylinder(radius,color,height);
         System.out.println("Area:" +obj1.calculateArea(radius));
         System.out.println("Volume of cylinder:" +obj1.calculateVolume(radius, height));         
    }
    
}


OutPut:



Post a Comment

0 Comments