What are nested interfaces in Java?

Java 8Object Oriented ProgrammingProgramming

An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.

To create an object of this type you need to implement this interface, provide body for all the abstract methods of the interface and obtain the object of the implementing class.

Nested interfaces

Java allows writing/declaring interfaces within another interface or, within a class these are known as nested interfaces.

Example

In the following Java example, we have a class with name Sample which contains a nested interface named myInterface.

In the class Sample we are defining a nested class named InnerClass and implementing the nested interface.

public class Sample {
   interface myInterface{
      void demo();
   }
   class InnerClass implements myInterface{
      public void demo(){
         System.out.println("Welcome to Tutorialspoint");
      }
   }
   public static void main(String args[]){
      InnerClass obj = new Sample().new InnerClass();
      obj.demo();
   }
}

Output

Welcome to Tutorialspoint

You can also implement the nested interface using class name as −

Example

class Test {
   interface myInterface{
      void demo();
   }
}
public class Sample implements Test.myInterface{
   public void demo(){
      System.out.println("Hello welcome to tutorialspoint");
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.demo();
   }
}

Output

Hello welcome to tutorialspoint
raja
Published on 08-Jul-2019 17:27:55
Advertisements