What is an Inner Interface in Java?
Join the DZone community and get the full member experience.
Join For Free
inner interface is also called nested interface, which means declare an interface inside of another interface. for example, the entry interface is declared in the map interface.
public interface map { interface entry{ int getkey(); } void clear(); }
why use inner interface?
there are several compelling reasons for using inner interface:
- it is a way of logically grouping interfaces that are only used in one place.
- it increases encapsulation.
- nested interfaces can lead to more readable and maintainable code.
one example of inner interface used in java standard library is java.util.map and java.util.map.entry. here java.util.map is used also as a namespace. entry does not belong to the global scope, which means 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.
how inner interface works?
to figure out how inner interface works, we can compare it with nested classes. nested classes can be considered as a regular method declared in outer class. since a method can be declared as static or non-static, similarly nested classes can be static and non-static. static class is like a static method, it can only access outer class members through objects. non-static class can access any member of the outer class.
because an interface can not be instantiated, the inner interface only makes sense if it is static. therefore, by default inter interface is static, no matter you manually add static or not.
a simple example of inner interface?
map.java
public interface map { interface entry{ int getkey(); } void clear(); }
mapimpl.java
public class mapimpl implements map { class implentry implements map.entry{ public int getkey() { return 0; } } @override public void clear() { //clear } }
Published at DZone with permission of Ryan Wang. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments