How to write/declare an interface inside a class in Java?


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.

 Live Demo

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

 Live Demo

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

Updated on: 29-Jun-2020

741 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements