Hierarchical Inheritance in Java


The program is an example of Hierarchical inheritance, where multiple child classes extend from a single parent class.

  • In this program, there is a parent class shape which has three float variables length, breadth, and radius. Then there are three child classes rect, circle, and square, which inherit from the shape class.
  • The rect class has a constructor that initializes the length and breadth variables, and a method rectangle_area() which returns the area of the rectangle.
  • The circle class has a constructor that initializes the radius variable, and a method circle_area() which returns the area of the circle.
  • The square class has a constructor that initializes the length variable, and a method square_area() which returns the area of the square.
  • Finally, in the main method, objects of each child class are created and their respective area calculation methods are called and printed.

Source Code

//Hierarchical Inheritance in Java
class shape {
    float length, breadth, radius;
}
class rect extends shape {
    public rect(float l, float b) {
        length = l;
        breadth = b;
    }
    float rectangle_area() {
        return length * breadth;
    }
}
class circle extends shape {
    public circle(float r) {
        radius = r;
    }
    float circle_area() {
        return 3.14f * (radius * radius);
    }
}
class square extends shape {
    public square(float l) {
        length = l;
    }
 
    float square_area() {
        return (length * length);
    }
}
 
 
public class Hierarchical {
    public static void main(String[] args) {
 
        rect o1 =new rect(2,5);
        System.out.println("Area of Rectangle : "+o1.rectangle_area());
 
        circle o2 =new circle(5);
        System.out.println("Area of Circle : "+ o2.circle_area());
 
        square o3 =new square(3);
        System.out.println("Area of Square : "+o3.square_area());
 
    }
}
 

Output

Area of Rectangle : 10.0
Area of Circle : 78.5
Area of Square : 9.0
To download raw file Click Here

Basic Programs