Can we define an interface inside a Java class?


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();
   }
}

Updated on: 16-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements