The perfect place for easy learning...

Java Programming

×

Topics List


Nested Interfaces in java





In java, an interface may be defined inside another interface, and also inside a class. The interface that defined inside another interface or a class is konwn as nested interface. The nested interface is also refered as inner interface.

🔔 The nested interface declared within an interface is public by default.

🔔 The nested interface declared within a class can be with any access modifier.

🔔 Every nested interface is static by default.


The nested interface cannot be accessed directly. We can only access the nested interface by using outer interface or outer class name followed by dot( . ), followed by the nested interface name.

Nested interface inside another interface

The nested interface that defined inside another interface must be accessed as OuterInterface.InnerInterface.

Let's look at an example code to illustrate nested interfaces inside another interface.

Example
interface OuterInterface{
	void outerMethod();
	
	interface InnerInterface{
		void innerMethod();
	}
}

class OnlyOuter implements OuterInterface{
	public void outerMethod() {
		System.out.println("This is OuterInterface method");
	}
}

class OnlyInner implements OuterInterface.InnerInterface{
	public void innerMethod() {
		System.out.println("This is InnerInterface method");
	}
}

public class NestedInterfaceExample {

	public static void main(String[] args) {
		OnlyOuter obj_1 = new OnlyOuter();
		OnlyInner obj_2 = new OnlyInner();
		
		obj_1.outerMethod();
		obj_2.innerMethod();
	}

}

When we run the above program, it produce the following output.

Nested interfaces in java

Nested interface inside a class

The nested interface that defined inside a class must be accessed as ClassName.InnerInterface.

Let's look at an example code to illustrate nested interfaces inside a class.

Example
class OuterClass{
	
	interface InnerInterface{
		void innerMethod();
	}
}

class ImplementingClass implements OuterClass.InnerInterface{
	public void innerMethod() {
		System.out.println("This is InnerInterface method");
	}
}

public class NestedInterfaceExample {

	public static void main(String[] args) {
		ImplementingClass obj = new ImplementingClass();
		
		obj.innerMethod();
	}

}

When we run the above program, it produce the following output.

Interfaces in java

In the next tutorial, we will learn about variables in interfaces.