java – Why do interfaces make life easier?

Question:

I have never written my own interfaces to "make life easier" before. Why? What's so interesting about them?

In the comments, I was asked to add my knowledge and area of ​​work to the question. I write android applications and … That's it. I don't know anything about interfaces, only that a class can inherit from an interface and override methods. But why? The meaning of interfaces?

Thanks for the great answers!

Answer:

An interface provides a contract that all classes that implement that interface must fulfill, and is an abstraction showing what an object can do, but how it does it is not important.

In practice, this leads to the following:

When using interfaces, it becomes possible to replace one class that implements the interface with another class that implements the same interface, without rewriting the entire code. For example, if a Map passed to the method:

public void handle(Map map) { ... }

you don't have to change the method description if you need to use TreeMap instead of HashMap .
Likewise, if a method returns a Map : it can start returning a TreeMap instead of a HashMap , and a biblical tragedy will not happen, since the code working with the value returned by this method deals with a Map .
This increases the flexibility of the code: it is easier to switch from one data source to another and from one implementation to another.
It is also useful for testing, as it allows you to use Mock objects instead of real ones.


If you need to treat collections of elements in the same way (for example, ArrayList and Set returned by the keySet() method of HashMap ), then it is enough to describe the method as follows:

public <T> void handle(Collection<T> elements) { ... }

Using generics here for more realism. Without using the interface, I had to create two methods:

public <T> void handle(ArrayList<T> elements) { ... }

public <T> void handle(Set<T> elements) { ... }

And either duplicate the code, or, for example, in the second method, create an ArrayList , add all the elements from the Set and call the first method.


Also, the use of interfaces allows you to combine different objects that implement the same interface into one list and treat them the same way:

public interface Animal
{
    public void feed();
}

public class Dog implements Animal
{
    public void feed() { ... }
}

public class Cat implements Animal
{
    public void feed() { ... }
}

List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
for (Animal animal : animals)
{
    animal.feed();
}

Without using the interface, you would have to fence "if-else" (or "switch-case") with a separate implementation of logic for each type of animal.

Scroll to Top