4

why is this line valid in java

I have just copied a line of the program , if you could explain it to me. Thanks

Runnable r[] = new Runnable[5];
Manjunath
  • 43
  • 5

4 Answers4

3

new Runnable[5] creates an array of Runnable type. It does not instantiate Runnable.

The invalid code would be the one caling new Runnable(). In other words, what is not allowed is the direct instantiation of an interface type, but you could create an array whose type is an interface.

ernest_k
  • 39,584
  • 5
  • 45
  • 86
1

By delaring a Runable array, you are not creating any object of the Runable interface, but an object of a certain java array class. So the compiler will not give any error. You are just declaring an array in which the elements must be objects of certain classes, which implements the Runable interface.

From JLS:

Every array has an associated Class object, shared with all other arrays with the same component type. [This] acts as if: the direct superclass of an array type is Object [and] every array type implements the interfaces Cloneable and java.io.Serializable.

ZhaoGang
  • 3,447
  • 18
  • 28
1

You are not initializing any of the elements with this line, so you haven't implemented the interface. You don't need to at this point, you are allocating space for the array of type interface. Later in the program, the elements are likely initialized and when they are they are done with implementations of the interface and not the interface itself.

1

It’s only an array of references, and the initialization is not complete until the reference itself is initialized by creating a new Runnable object.

As this answer clearly states :

For references (anything that holds an object) that is null.

and you can always write:

interface Foo{}

Foo foo = null;
Saurav Sahu
  • 9,755
  • 5
  • 42
  • 64