Sobes.tech
Junior — Middle

How to implement and use interfaces in Java to define contracts between classes?

sobes.tech AI

Answer from AI

In Java, interfaces are used to define contracts between classes — they describe a set of methods that a class must implement without specifying the actual implementation.

How to implement and use interfaces:

  1. Declaring an interface:
public interface Vehicle {
    void start();
    void stop();
}
  1. Implementing the interface in a class:
public class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car is starting");
    }

    @Override
    public void stop() {
        System.out.println("Car is stopping");
    }
}
  1. Using the interface to work with objects of different classes that implement the same contract:
public void operateVehicle(Vehicle v) {
    v.start();
    // ...
    v.stop();
}

Advantages:

  • Ensures standardization of methods.
  • Allows the use of polymorphism.
  • Simplifies maintenance and extension of code.

Thus, interfaces define a mandatory set of methods that must be implemented by classes, providing a unified interaction contract.