Interface in java
Question:
Write a Java program to create an interface Shape with the calculateArea() method. Create three classes Rectangle, Circle, and Triangle that implement the Shape interface. Override the calculateArea() method in each subclass to calculate and return the shape's area.
💡 Solutions (1)
Super Admin
AdminFeb 03, 2026 at 05:31
upvotes
interface Shape { double calculateArea(); } class Rectangle implements Shape { private final double length; private final double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double calculateArea() { return length * width; } } class Circle implements Shape { private final double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } } class Triangle implements Shape { private final double base; private final double height; public Triangle(double base, double height) { this.base = base; this.height = height; } @Override public double calculateArea() { return 0.5 * base * height; } } public class ShapeDemo { public static void main(String[] args) { Shape rectangle = new Rectangle(10, 5); Shape circle = new Circle(7); Shape triangle = new Triangle(8, 6); System.out.println("Rectangle area: " + rectangle.calculateArea()); System.out.println("Circle area: " + circle.calculateArea()); System.out.println("Triangle area: " + triangle.calculateArea()); } }
Want to add your solution? Login to contribute!
🔄 This question has been converted to a program
View Program →💬 Comments (0)
Login to post comments
No comments yet
Be the first to comment!