Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What is an Inner Interface in Java?

DZone's Guide to

What is an Inner Interface in Java?

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

java-nested-classes

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
	}
}


Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Ryan Wang. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}