Write a Java program to demonstrate the use of implementing interfaces
Example image of Write a java program to demonstrate use of implementing interfaces ? |
Here's a simple Java program that demonstrates implementing interfaces with the example :
java
// Define an interface
interface Shape {
double area();
double perimeter();
}
// Implement the interface in a 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);
}
}
// Another class implementing the interface
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;
}
}
// Main class to test
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
Circle circle = new Circle(3);
// Using methods defined in the interface
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Rectangle perimeter: " + rectangle.perimeter());
System.out.println("Circle area: " + circle.area());
System.out.println("Circle perimeter: " + circle.perimeter());
}
}
In this example:
- We define an interface called `Shape` with two methods: `area()` and `perimeter()`.
- We implement this interface in two classes: `Rectangle` and `Circle`.
- Each class provides its own implementation for the methods defined in the `Shape` interface.
- In the `Main` class, we create instances of `Rectangle` and `Circle` and call the methods `area()` and `perimeter()` on them, demonstrating polymorphism through interface implementation.
Post a Comment