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];
4
  • 1
    we can't create objects for interfaces , iam confuse on these line Commented Dec 10, 2018 at 5:01
  • But you can make classes that implement the Runnable interface, and you can make objects of those classes. Objects of classes that implement Runnable are what you you would store in this array. Commented Dec 10, 2018 at 5:06
  • 1
    Runnable[] isn't an object of Runnable, it's a container that holds Runnable objects. Commented Dec 10, 2018 at 5:15
  • specification allows it Commented Dec 10, 2018 at 5:33

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.