2

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];
}
3
  • change it to array Runnable[] run = new Runnable[5]; Commented Apr 27, 2014 at 11:20
  • @Braj The question is why the first one does not fail, not why the second one does fail. Commented Apr 27, 2014 at 11:25
  • @Thirler I have already posted an answer. Commented Apr 27, 2014 at 11:27

3 Answers 3

8

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.

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

Comments

0

array is Serializable that why its fine to say

Serializable serial = new Serializable[5];

2 Comments

This is a bit opaque, especially as to new programmers it may appear a tautology. Perhaps a demonstration is in order?
@Clockwork-Muse Jon Skeet has already has described it. So I don't need to explain it more.
0

The second one should be obvious. We would expect Runnable[] run.... The first one is not that obvious. It is because an array of Serializable does implement the Serializable interface - in a hidden way. So an array can be considered as a Serializable object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.