Last Updated: 28 May, 2022
An interface defined inside another interface or a class is known as Nested Interface in Java. A nested interface is used to increase encapsulation It groups interfaces that are related or used in one place for more readable and maintainable code.
Nested Interface is always accessed outside with its outer interface or outer class name but it cannot be accessed outside directly.
For example, java.util.Map.Entry
interface defined inside java.util.Map
interface. We access it as Map.Entry
, because Entry is a nested interface of Map Interface.
Let's have a look at the below-given syntax for more clarity.
Syntax: Nested Interface within an Interface and Class
|
|
There are the following important points about Nested Interface
Java allows to create an interface inside another interface, it must be accessed outside as OuterInterfaceName.NestedInterfaceName but not directly.
Example 1 : Nested Interface implementation within an Interface
Output
Outer Interface - method1() called...
Nested Interface - method2() called...
Java allows to create an interface inside a class, it must be accessed outside as OuterClassName.NestedInterfaceName but not directly.
Example 2 : Nested Interface implementation within a Class
Output
MyNestedInterface - myMethod() called...
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What are the benefits of using Nested Interface in Java?
Ans. Nested Interface provides the following benefits in Java programming:
How we can implement a nested interface outside the outer interface or outer class?
Nested Interface is always accessed outside with its outer interface or outer class name only. For example, OuterInterfaceName.NestedInterfaceName
OuterClassName.NestedInterfaceName
Does the Java compiler create a separate .class file for nested interfaces?
Yes, the Java compiler creates a separate .class file for nested interfaces, whose name is made with a combination of outer and nested interface names with a $ sign in between.
How many nested interfaces we can create inside a class or interface?
There is no limitation, we can create any number of nested interfaces inside a class or interface in Java.
Can we define a class inside the interface?
Ans. Yes, Java allows defining a class inside the interface.
interface OuterInterfacce {
class InnerClass{}
}