Why declare an interface inside an interface?

This is a simplified version of java.util.Map

public interface Map { interface Entry{ int getKey(); } void clear(); } 

My question is, why is this done this way?

How should the internal interface be implemented? Can I just implement internal?

+4
source share
2 answers

I'm going to be ... terribly theoretical here ... so keep an open mind, please. A separate Entry interface separates this concept from the context to which it is intended. Do not think only about the interface, but about its implementations. Take, for example, the internal static Entry class defined in HashMap :

 static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; final int hash; (...) } 

This Entry class is not intended to be used externally, and the interface that it implements is a maintenance contract intended only for internal use between Map s, in particular because Map is the interface itself and needs a little abstraction so that specific implementations define The type of record they will use.

In fact, I'm sure you are wondering: "Of course, but a record can be used in many situations, especially if you need a Key-Value pair." This is true, but I personally agree with the current design decision, as it provides everything that is needed to implement Map in one place.

+5
source

Here Map is also used as a namespace. This is because Entry does not belong to the global scope - there are many other objects that Entries are not necessary Map elements. This means that Entry represents Map related entries.

+5
source

Source: https://habr.com/ru/post/1498270/


All Articles