Implementing Interfaces in Java
In Java, an interface is a contract that defines a set of methods that a class must implement. Interfaces provide a way to achieve abstraction and promote code reusability. By implementing an interface, a class agrees to provide the implementation for the methods defined in the interface.
Here's how you can implement an interface in Java:
-
Defining an Interface:
An interface is defined using theinterface
keyword. It can contain method declarations, default methods, static methods, and constants (public static final variables).interface Vehicle { void start(); void accelerate(); void brake(); int getMaxSpeed(); }
-
Implementing an Interface:
To implement an interface, a class uses theimplements
keyword followed by the name of the interface(s) it wants to implement.class Car implements Vehicle { private int currentSpeed; private int maxSpeed; public Car(int maxSpeed) { this.maxSpeed = maxSpeed; this.currentSpeed = 0; } @Override public void start() { System.out.println("Car started."); } @Override public void accelerate() { if (currentSpeed < maxSpeed) { currentSpeed += 10; System.out.println("Car is accelerating. Current speed: " + currentSpeed + " km/h"); } else { System.out.println("Car has reached its maximum speed."); } } @Override public void brake() { if (currentSpeed > 0) { currentSpeed -= 10; System.out.println("Car is braking. Current speed: " + currentSpeed + " km/h"); } else { System.out.println("Car is already stopped."); } } @Override public int getMaxSpeed() { return maxSpeed; } }
In the example above, the
Car
class implements theVehicle
interface. TheCar
class must provide the implementation for all the methods defined in theVehicle
interface. -
Using an Implemented Interface:
Once a class has implemented an interface, you can create instances of that class and call the methods defined in the interface.Vehicle myCar = new Car(180); myCar.start(); myCar.accelerate(); myCar.accelerate(); myCar.brake(); System.out.println("Max speed: " + myCar.getMaxSpeed() + " km/h");
The output of the above code will be:
Car started. Car is accelerating. Current speed: 10 km/h Car is accelerating. Current speed: 20 km/h Car is braking. Current speed: 10 km/h Max speed: 180 km/h
Here's a Mermaid diagram that illustrates the concept of implementing an interface in Java:
Implementing interfaces in Java is a fundamental concept that allows for code reuse, abstraction, and polymorphism. By defining a contract (the interface) and having classes implement that contract, you can write code that is more flexible, maintainable, and scalable.