7

In Java, we use Interface to hide the implementations from users. Interface contains only abstract methods and as abstract methods do not have a body we can not create an object without constructor. Something like this

public interface ExampleInterface {
}
public class Example implements ExampleInterface {
    private static void main(String[] args) {
        // This is not possible
        ExampleInterface objI = new ExampleInterface();

        // However this is
        ExampleInterface[] arrI = new ExampleInterface[10];
    }
}

My question is why Java allows creating an array of object Interface and where someone might use it? Is is a good coding practice to use it or it is better to create a concrete class that implements the interface and then create an array of that class.

1 Answers1

7

Note that creating an array of interfaces is not the same as creating an instance of an interface. By allowing you to create arrays of interfaces, it doesn't imply that you can also create instances of interfaces now.

Let's give ExampleInterface a method for the sake of argument:

public interface ExampleInterface {
    void foo();
}

When you do this:

ExampleInterface[] arrI = new ExampleInterface[10];

You are just creating an array of ten elements that looks like this:

{ null, null, null, null, null, null, null, null, null, null }

Why null? Because that is the default value for any reference type.

As you can see, there aren't any instances of ExampleInterface magically created by using that line above. To replace those nulls, you still have to use a class that implements ExampleInterface or get an instance from somewhere else:

arrI[0] = new ExampleInterfaceImplementer();
// arrI[0] = new ExampleInterface(); // this still doesn't work

At the end of the day, we still don't know what the implementation of foo looks like for arrI[0] or arrI[1] or array[2], and so on, so nothing is broken.

Is it a good coding practice to use it or it is better to create a concrete class that implements the interface and then create an array of that class?

Well, it's not a bad practice. Sometimes you cannot always do the latter. What if you want to store instances of both A and B, which both implement ExampleInterface?

Related: What does it mean to "program to an interface"?

Sweeper
  • 213,210
  • 22
  • 193
  • 313