Can we define an interface inside a Java class?

Java 8Object Oriented ProgrammingProgramming

Yes, you can define an interface inside a class and it is known as a nested interface. You can’t access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

Example

Live Demo

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

Output

Welcome to Tutorialspoint

You can also access the nested interface using the 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();
   }
}
raja
Published on 10-Jan-2018 17:14:46
Advertisements