0

As i know that Object is the super most class of all classes in java. But, below code i am not able to understand. please help me out.

Object c = new long[4];
Object d = new int[4];
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147

4 Answers4

7

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array

From the Java Language Specification.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
4

As written, this should give you an error because you are re-declaring a variable named c. However, the following is perfectly valid:

Object c = new long[4];
c = new int[4];

This works because, as you say, Object is the superclass of all non-primitive types in Java.

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152
2

It compiles because every array in Java is an object, too.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Object is the super class of arrays in Java (mentioning just arrays because the question demands so).

So when you assign a long array to object it is internally type casted to Object.

Similarly for int. So in the end in both statements the variable on the right is an Object. However, you cannot have Object c = in both the lines.

JHS
  • 7,761
  • 2
  • 29
  • 53