FAQ

Java

JSP

Servlet


Advertisement



Can an anonymous inner class implement an interface?

Yes. An anonymous inner class can implement interface or extends class. Anonymous inner interfaces are always implicitly static.

Here is how to create an instance of inner class and inner interface:

  • Anonymous Inner Class

    class Outer{
    abstract class InnerClass {
    abstract void doSomething();
    }
    }

    public class Program {
    public Program() {
    super();
    }

    public static void main(String[] args) {
    Outer.InnerClass obj = new Outer().new InnerClass(){
    public void doSomething(){
    System.out.println("InnerClass.");
    }
    };
    obj.doSomething();
    }

    }
  • Anonymous Inner Interface:

    class Outer{
    interface InnerInterface {
    void doSomething();
    }
    }

    public class Program {
    public Program() {
    super();
    }

    public static void main(String[] args) {
    Outer.InnerInterface obj = new Outer.InnerInterface() {
    public void doSomething(){
    System.out.println("InnerInterface.");
    }
    };
    obj.doSomething();
    }

    }


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |