1

I understood that java interface cannot be instantiated. However, the below code looks like it instantiated an interface ? I'm trying to understand the code.

interface I{
    int a();
    int b();
}

public class C {
    public static void main(String [] arg){
    I i=(new I(){
        public int a(){return 1;}
        public int b(){return 2;}
    });
    assert i.a()==1 && i.b()==2;
    }
}
Osca
  • 1,588
  • 2
  • 20
  • 41

1 Answers1

2

An interface is like an all-abstract class, but that unambiguously supports multiple inheritance. You can instantiate any child of it that implements all the abstract methods.

The code you are asking about is creating an anonymous class that provides an implementation of all the abstract methods. Since the class is anonymous, the type of its instance can is most specifically given as I. Given that it's anonymous, that's also the only aspect of it you care about.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264