Thursday, 25 August 2016

Java Nested Interface

A nested interface is any regular interface whose declaration occurs within another class or interface. These interfaces are used to group related interfaces so that we can be easy to maintain.

Rules for Declaring Nested Interface
1. Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.

2. Nested interfaces are implicitly static regardless of where they are declared (inside class or another interface).

interface OuterInter {
     void outerMethod();
     interface InnerInter {
           void method();

class NestedInterface implements OuterInter.InnerInter {
     public void method() {
           System.out.println("Hello nested interface");

     public static void main(String args[]) {
           OuterInter.InnerInter message = new NestedInterface();//up-casting here

Output: Hello nested interface

Application Use of Nested Interfaces

A static nested interface serves a great advantage to namespace resolution. This is the basic idea behind introducing nested interfaces and nested classes in Java.

For example, if you have an interface with an exceedingly common name, and in a large project, it is quite possible that some other programmer has the same idea, and has an interface with the same name you had, then you can solve this potential name clash by making your interface a public static nested interface.

Your interface will be known as outer class or outer interface, followed by a period (.), and then followed by static nested interface name.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...