1

We know that Arrays are objects in Java. I believe to create an object in Object oriented languages(if not we can have it in a separate discussion), we need a blueprint of it(a class). But I'm not sure or cannot find the class for which the object is being created for arrays when the new operator is used. If there is a class for arrays in java, then how will the hierarchy look like?

If there is no class, then how are the objects instantiated? And what is the reason behind having an object type without a class?

Arun
  • 2,562
  • 6
  • 25
  • 43
  • ay89: I know that the arrays are objects in java. But I want to know if there is a benefit in having an object without a class(if there is one) for it. – Arun May 14 '13 at 06:51
  • 1
    Question starts with "We know that Arrays are objects in Java.", then people duplicate it to a question titled "Is an array an object in java". Hilarious. – auselen May 14 '13 at 07:14
  • auselen: you are right :) – Arun May 14 '13 at 07:17
  • Down-voter: Can I know why my question is down-voted? – Arun May 15 '13 at 11:00

5 Answers5

3

Arrays are created by virtual machine with a special instruction called newarray, so think them as a special construct.

From JVM Spec:

3.9. Arrays

Java Virtual Machine arrays are also objects. Arrays are created and manipulated using a distinct set of instructions. The newarray instruction is used to create an array of a numeric type. The code:

Also read more from JLS for class hierarchy of an array.

The direct superclass of an array type is Object.

auselen
  • 27,577
  • 7
  • 73
  • 114
2

An array, let's say an Object[], is a special kind of variable, just as primitives are. Its type is Object[], not Object. Java is not a "fully" object oriented language, such as Ruby is; it has some special data types like arrays and primitives.

Andrea Bergia
  • 5,502
  • 1
  • 23
  • 38
1

The logic is reverse to your.

An object is a class instance or an array.

But as Java is OOP language, everything must be represented as object. When you reflect your code you can use class java.lang.reflect.Array that represent Array.

Community
  • 1
  • 1
1

arrays are not primitive in java. An array is a container object that holds a fixed number of values of a single type.

System.out.print(int[].class.toString());

It successfully prints and proves it has a concrete class in background and same applied for all other array types.

Find documentaion in detail.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

Yes, Java has classes for arrays, see http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.8 Class Objects for Arrays, e.g.

Class<int[]> cls = int[].class;

These classes are dynamically created by JVM.

There is no hierarchy among arrays of primitive types

   int[] a = new long[1];

Produces compile time error. The hiearchy of Object array types is the same as with Object types

Object[] a = new String[1];
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275