Sobes.tech
Junior — Middle

What are the advantages of using interfaces to organize interaction with various objects?

sobes.tech AI

Answer from AI

Using interfaces in Java allows defining a contract for interaction without binding to a specific implementation. This provides several advantages:

  • Abstraction: you can work with objects through a common interface without knowing the implementation details.
  • Flexibility and extensibility: it's easy to add new implementations without changing the code that uses the interface.
  • Polymorphism support: objects of different classes can be used interchangeably if they implement the same interface.
  • Simplified testing: real implementations can be replaced with mocks or stubs.

Example:

interface Printable {
    void print();
}

class Document implements Printable {
    public void print() {
        System.out.println("Printing document");
    }
}

class Photo implements Printable {
    public void print() {
        System.out.println("Printing photo");
    }
}

// Usage
Printable item = new Document();
item.print(); // Printing document

item = new Photo();
item.print(); // Printing photo