I'd like to point out this article. It seems as though arrays and objects follow different opcodes. I can't honestly summarize it more than that however it seems, arrays are simply not treated as Objects
like we're normally used to so they don't inherit Object
methods.
Full credits to the author of that post as it's a very interesting read, both short & detailed.
Upon further digging into the topic via multiple sources I've decided to give a more elaborate version of my previous answer.
The first thing to note that instantiation of Objects and Arrays are very different within the JVM, their follow their respective bytecode.
Object:
Object
instantiation follows a simple Opcode new
which is a combination of two operands - indexbyte1
& indexbyte2
. Once instantiated the JVM pushes the reference to this object onto the stack
. This occurs for all objects irrespective of their types.
Arrays:
Array
Opcodes (regarding instantiation of an array) however are divided into three different codes.
newarray
- pops length, allocates new array of primitive types of type indicated by atype, pushes objectref of new array
newarray
opcode is used when creating arrays that involve primitive datatypes (byte
short
char
int
long
float
double
boolean
) rather than object references.
anewarray
- pops length, allocates a new array of objects of class indicated by indexbyte1 and indexbyte2, pushes objectref of new array
anewarray
opcode is used when creating arrays of object references
multianewarray
- pops dimensions number of array lengths, allocates a new multidimensional array of class indicated by indexbyte1 and indexbyte2, pushes objectref of new array
multianewarray
instruction is used when allocating multi-dimensional arrays
Object can be a class instance or an array.
Take from Oracle Docs
A class instance is explicitly created by a class instance creation expression
BUT
An array is explicitly created by an array creation expression
This goes hand in hand with the information regarding the opcodes. Arrays are simply not developed to be class interfaces but are instead explicitly created by array creation expression thus naturally wouldn't implicitly be able to inherit and/or override Object
.
As we have seen, it has nothing to do with the fact that arrays may hold primitive datatypes. After giving it some thought though, it isn't very common to come across situations where one might want to toString()
or equals()
however was still a very interesting question to try and answer.
Resources:
Oracle-Docs chapter 4.3.1
Oracle-Docs chapter 15.10.1
Artima - UnderTheHood