Certainly! Here's an example of Java code that represents an inheritance hierarchy with three subclasses using the is-a relationship:
class Shape {
String name;
public Shape(String name) {
this.name = name;
}
public void draw() {
System.out.println("Drawing a " + name);
}
}
class Circle extends Shape {
double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}
public void calculateArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of the " + name + ": " + area);
}
}
class Rectangle extends Shape {
double length;
double width;
public Rectangle(String name, double length, double width) {
super(name);
this.length = length;
this.width = width;
}
public void calculateArea() {
double area = length * width;
System.out.println("Area of the " + name + ": " + area);
}
}
class Triangle extends Shape {
double base;
double height;
public Triangle(String name, double base, double height) {
super(name);
this.base = base;
this.height = height;
}
public void calculateArea() {
double area = 0.5 * base * height;
System.out.println("Area of the " + name + ": " + area);
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle("Circle", 5.0);
circle.draw();
circle.calculateArea();
Rectangle rectangle = new Rectangle("Rectangle", 4.0, 6.0);
rectangle.draw();
rectangle.calculateArea();
Triangle triangle = new Triangle("Triangle", 3.0, 4.0);
triangle.draw();
triangle.calculateArea();
}
}
In this code example, we have a base class Shape that is inherited by three subclasses: Circle, Rectangle, and Triangle. Each subclass represents a specific shape and has additional attributes and behaviors specific to that shape. The Shape class has a name attribute common to all shapes and a draw() method that is inherited by the subclasses.
The Circle class represents a circle, with an additional attribute radius and a calculateArea() method specific to circles. The Rectangle class represents a rectangle, with additional attributes length and width, and a calculateArea() method specific to rectangles. The Triangle class represents a triangle, with additional attributes base and height, and a calculateArea() method specific to triangles.
When running the code, it will output:
Drawing a Circle
Area of the Circle: 78.53981633974483
Drawing a Rectangle
Area of the Rectangle: 24.0
Drawing a Triangle
Area of the Triangle: 6.0
This demonstrates how the subclasses of Circle, Rectangle, and Triangle inherit the common properties and behavior from the parent class Shape, but also have their own specific attributes and behaviors.