I have never written my own interfaces to "simplify life." Why? What is so interesting about them?

The comments asked to add to the question my knowledge and area of ​​work. I write android applications and ... Everything. I do not know anything about interfaces, only that it is possible to inherit and override a class from an interface. But why? The meaning of interfaces?

Thanks for the wonderful answers!

  • Try adding to the question what you know about interfaces (maybe there are gaps in knowledge) and what kind of applications / code you write (maybe you don’t need them). - Kromster
  • Updated the question. - Flippy
  • a class does not inherit methods of interface, it implements them - Bohdan Korinnyi
  • It would be easier to answer that the necessary code structure is implemented by the interfaces, and then you need to ask, and why? - Shwarz Andrei

4 answers 4

For me personally, the most obvious for understanding the essence of interfaces are collections and everything connected with them. Most likely this is the case, because they often had to work with them.

One of the main features of OOP is getting rid of duplication of logic, due to the correct architectural component. For this case (in a general sense), interfaces and abstract classes were invented.

Suppose I have a spherical method in vacuum that does some work with the collection:

/*Здесь может быть любой тип коллекции, который реализует соотв. интерфейс. Причем я использую интерфейс самого "низкого" уровня, т.к. он полностью покрывает данный функционал (т.е. проход по элементам в цикле) Также я могу написать любую свою реализацию для этого интерфейса */ public void showCollectionAtConsole(Iterable<?> col){ col.forEach(object -> System.out.println(object)); } 

The convenience here is that only in Java itself there are quite a few implementations of this interface, ( more ) and I can use this logic for each of them.

Now I have another method that implements some kind of functional:

 public boolean removeOrAddMyObject (Collection<MyObject> col, MyObject object){ //Если удалил объект - true, иначе - false boolean isRemove = true; if (col!=null){ if (col.isEmpty() || !col.remove(object)) { col.add(object); isRemove = false; } }else throw new IllegalStateException("Коллекция = null"); return isRemove; } 

Here I have to use three collection methods: isEmpty (), add (), remove (). However, all these methods are described in the Collection interface, and there is no need to pass as a “higher” interface or class with an implementation as an argument. As I wrote above, this solution will allow me with a clear conscience to reuse this method repeatedly for other implementations.

Also, it seems to me that Callbacks are an excellent example of using interfaces:

 public final class MyClass { static class MyObject { int id; String name; public MyObject(int id, String name) { this.id = id; this.name = name; } public void setId(int id) { this.id = id; } public void setName(String name){ this.name = name; } @Override public String toString(){ return "My Object: id = "+id+", name = "+name; } } //Интерфейс коллбэка interface MyCallback<T extends MyObject> { void doSome(T myObject); } static void doSomeAwesome(MyObject object, MyCallback<MyObject> callback) { System.out.println(object); callback.doSome(object); System.out.println(object); } public static void main(String[] args) { MyObject myObject = new MyObject(1,"someName"); MyCallback<MyObject> callback = new MyCallback<MyObject>() { @Override public void doSome(MyObject myObject) { myObject.setId(2); myObject.setName("someOtherName"); } }; doSomeAwesome(myObject,callback); } } 

The bottom line is that you explicitly define a generic in the callback interface (if you want to pass parameters to the method and / or receive objects from the method) and describe the contract. In my case, this is one method that takes an argument as input. Now, I can implement the callback method as I see fit, and thus extend the use of the doSomeAwesome() method doSomeAwesome() additional logic.

If you execute the code at the output will be:

My Object: id = 1, name = someName

My Object: id = 2, name = someOtherName

UPD: You should also understand that there are other contexts for using interfaces:

  • multiple inheritance context (in Java, you cannot inherit from more than 1 class, but you can implement more than 1 interface)
  • interface as a layer between interacting entities. Those. There are two modules in the program that perform different functions while interacting with each other. In an ideal situation, both modules should represent a black box for each other with the necessary minimum of methods described by the interfaces. Thus, it is much easier to avoid difficulties with subsequent debugging of the code.
  • application architecture design context. As a rule, at the initial stage of designing the architecture of a future application, it is very convenient to “figure out” the interaction between entities using interfaces. It is as if the draft, which does not require a “bother” with the implementation, and allows for relatively painless modification of the architecture at the early stages.
  • testing context. As already mentioned in one of the answers, the use of interfaces allows you to: "use Mock objects instead of real ones". Believe me, in the future it makes life very easy.

    The interface provides a contract that all classes implementing this interface must perform and is an abstraction that shows what an object can do, but how it does this is not important.

    In practice, this leads to the following:

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

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

    you don’t have to change the method description if you want to use TreeMap instead of HashMap .
    Similarly, if the method returns a Map : it can start returning a TreeMap instead of a HashMap , and the tragedy of biblical scales will not happen, since the code that works with the value returned by this method deals with 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 the use of Mock objects instead of real ones.


    If you need to handle collections of elements in the same way (for example, ArrayList and Set , returned by the keySet() method), it suffices to describe the method like this:

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

    Use generics-type here for greater 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 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 process them in 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, I would have had to “if-else” (or “switch-case”) with a separate implementation of logic for each type of animal.

    • I will add my five kopecks, the interfaces greatly simplify life during testing. They allow locking dependent components to a specific behavior. - Artem Konovalov
    • @ArtemKonovalov yes, I wanted to mention the tests in the first paragraph, but then did not, limiting myself to more general words. Do you think it is worth explicitly indicate? - Regent
    • I think all the same it is worth adding, because this is really a useful property of using interfaces - Artem Konovalov
    • one
      @Regent >> The interface gives the contract << in these words Rust is directly felt)) - test123

    Because the interface is an abstraction that talks about what to do and not how to do it. "life simplification" is that the interface sets a uniform expected behavior, and wherever you meet it (unless of course the programmer spat on the interface contract). In general, to understand what I wrote here, you would read books on the PLO.

    • For example, look. I have a class for the adapter list RecyclerView . And a separate class Activity . In the adapter, I want to put a listener on the button. How can I make this listener work in the Activity class? Is there an "easier life" interface? - Flippy
    • @ SergeyGrushin What you are talking about here is not exactly what you are asking in the question. To solve the problem from the commentary, you need to ask about callbacks (callback interfaces) - this is not the same as in the question, or rather the question only about the part of the mechanism - the contract for the return value. - pavlofff
    • Yeah .. I just did not quite understand the essence of the interface. And what can you read on this topic, Kelbekov - Flippy

    Interfaces and in truth simplify life. Let's gps Google api in android for navigation gps Google api using the interface, for the listener using the interface (Interfaces are used almost everywhere even in streams) And starting with Java-8, the interfaces also implement the body, so you can write not only the condition but also the body of the interface. But it’s up to everyone to use them or not. It’s not always the programmer's responsibility to implement their interfaces. The rules "writing good code" says: first create interfaces abstraction and then implement))

    • You have described what is, but forgot to write, why do interfaces simplify life ? - Kromster
    • so that you do not write your own) saving time and code size - elik
    • five
      Some strange answer. “cars make life easier because they don’t have to make their own” .. but the question is probably why they are needed at all - Kromster