Understanding Interfaces in Java
Classes and Objects
In Java, an interface is a blueprint for a class that defines a set of methods that must be implemented by any class that chooses to adhere to the interface. An interface defines a contract of behavior that classes must follow but does not provide any implementation for these methods. Instead, the classes implementing the interface are responsible for providing their own specific implementations for the methods declared in the interface.
// Define the Shape interface
interface Shape {
double area(); // Method to calculate the area of the shape
double perimeter(); // Method to calculate the perimeter of the shape
}
// Implement the Shape interface in the Circle class
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}
// Implement the Shape interface in the Rectangle class
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width;
}
@Override
public double perimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
// Create a circle and calculate its area and perimeter
Circle circle = new Circle(5.0);
System.out.println("Circle Area: " + circle.area());
System.out.println("Circle Perimeter: " + circle.perimeter());
// Create a rectangle and calculate its area and perimeter
Rectangle rectangle = new Rectangle(4.0, 6.0);
System.out.println("Rectangle Area: " + rectangle.area());
System.out.println("Rectangle Perimeter: " + rectangle.perimeter());
}
}
Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Rectangle Area: 24.0
Rectangle Perimeter: 20.0
Comments
Post a Comment