Curriculum
In Java, an interface is a collection of abstract methods that defines a contract or a set of rules for classes that implement it. An interface specifies what methods a class should have, but it does not provide any implementation for those methods. It is up to the implementing class to provide the implementation for the methods defined in the interface.
Here’s an example to illustrate the concept of interfaces in Java:
interface Shape { double getArea(); double getPerimeter(); } class Rectangle implements Shape { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double getArea() { return width * height; } public double getPerimeter() { return 2 * (width + height); } } class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public double getPerimeter() { return 2 * Math.PI * radius; } }
In the example above, the Shape
interface defines two abstract methods, getArea()
and getPerimeter()
. The Rectangle
and Circle
classes both implement the Shape
interface, which means they must provide an implementation for both methods. The Rectangle
class provides an implementation for the methods by calculating the area and perimeter of a rectangle, while the Circle
class provides an implementation by calculating the area and circumference of a circle.
Here’s how you can use the Rectangle
and Circle
classes:
Shape shape1 = new Rectangle(10, 5); Shape shape2 = new Circle(7); System.out.println("Area of shape1: " + shape1.getArea()); System.out.println("Perimeter of shape1: " + shape1.getPerimeter()); System.out.println("Area of shape2: " + shape2.getArea()); System.out.println("Perimeter of shape2: " + shape2.getPerimeter());
In the example above, we create two instances of classes that implement the Shape
interface, one of type Rectangle
and one of type Circle
. We call the getArea()
and getPerimeter()
methods on both instances, and they each output the area and perimeter of their respective shape.
Here are some rules to keep in mind when working with interfaces in Java:
extends
keyword, allowing it to inherit the methods from those interfaces.