数据类型接口数组

7 java arrays interface

在Java中,我们使用Interface对用户隐藏实现。接口仅包含抽象方法,并且由于抽象方法没有主体,因此如果没有构造函数,我们将无法创建对象。像这样

public interface ExampleInterface {
}
Run Code Online (Sandbox Code Playgroud)
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];
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么Java允许创建对象接口数组,以及有人可以在哪里使用它?使用它是一种好的编码习惯,或者最好创建一个实现接口的具体类,然后创建该类的数组。

Swe*_*per 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();
}
Run Code Online (Sandbox Code Playgroud)

When you do this:

ExampleInterface[] arrI = new ExampleInterface[10];
Run Code Online (Sandbox Code Playgroud)

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

{ null, null, null, null, null, null, null, null, null, null }
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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"?