Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare an interface inside an interface? [duplicate]

Tags:

java

This is a simplified version of java.util.Map

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

    void clear();
}

My question is why it is done that way?

How the inner interface should be implemented? Can I just implement the inner one?

like image 835
Ryan Avatar asked Dec 26 '22 22:12

Ryan


2 Answers

I'm going to be... terribly theoric here... so keep an open mind, please. A separate Entry interface would decouple that concept from the context it is meant to. Don't think only about the interface but about its implementations. Take for example the Entry inner static 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 outside, and the interface it implements represents a service contract meant only for internal use amongst Maps, in particular because Map is an interface itself and needs a little abstraction to let the particular implementations define the kind of entry that they will use.

Indeed, I bet you're wondering "Sure, but an entry can be used in many situations, specially when you need a Key - Value pair". This is, in fact, true, but I personally agree with the current design decision as it provides everything that is required to implement a Map in a single place.

like image 168
Fritz Avatar answered Jan 11 '23 11:01

Fritz


Here Map is used also as a namespace. It's because Entry does not belong to the global scope - there are many other entities that are Entries and are not necessary Map's entries. This indicates that Entry represents entries related to the Map.

like image 35
BartoszKP Avatar answered Jan 11 '23 12:01

BartoszKP