Why cant we instantiate an interface but can do an array of interface?

Viewed 48

For example, this is valid and we need to have Class Two objects in this T array, what is the purpose of this acceptance?

interface One 
{
    public void callback();   
}

class Two implements One
{
    One[] T = new One[5];
}
1 Answers

Because you aren't instantiating an interface, you are instantiating an array. No interfaces are instantiated here:

One[] T = new One[5];

Every element of T will be null. Creating an instance could look like this:

class OneImpl implements One {
   @Override
   public void callback() {
      System.out.println("callback");
   }
}

T[0] = new OneImpl();

Or like this:

T[0] = new One() { 
    @Override
    public void callback() {
        System.out.println("callback");
    }
};

Or even like this:

T[0] = () -> System.out.println("callback");
Related