简体   繁体   中英

Array of Data Type Interface

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.

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 null s, 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"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM