Why first line of following method compiles while second not? I would expect both fail.
import java.io.Serializable;
public class ArrayConversions {
Serializable serial = new Serializable[5];
Runnable run = new Runnable[5];
}
The first line compiles because all arrays implement Serializable
. From the JLS section 10.8:
Although an array type is not a class, the Class object of every array acts as if:
The direct superclass of every array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.
So you could use:
Serializable serial = new int[10];
You happen to have created a Serializable[]
, but that's just a coincidence - it's not like you're meant to be able to assign an array type value to its element type value.
So your mistake can be seen for Object
as well:
Object o = new Object[10]; // Or new String[10] or new int[10] or whatever
... but these are just about what array types support.
See more on this question at Stackoverflow