Could it be implemented in the JVM without too many changes?
No. The changes would be massive. They would impact the entire Java tool chain, and also a huge body of 3rd-party code the works at or below the JLS / JVM abstraction layer.
There is nothing stopping you from downloading the (OpenJDK) source code and trying to do this yourself as an experiment. But the chances of this happening in real Java are (IMO) vanishingly small.
I've listed just some of the technical problems at the bottom. I'm sure that there are others.
Does the JVM treats arrays like any object with a class that can be inherited from?
No.
Array types in Java provide a small number of methods. (The methods are getClass
, hashCode
, toString
, clone
, wait
, notify
and notifyAll
... as per the Object
API.)
As far as I know, the actual implementations of these methods are provided by the native methods defined by java.lang.Object
. But since the JLS does no permit you to write code that inherits from an array, the JVM spec doesn't need to provide a way to implement such code. And, in practice, it doesn't.
Does the JVM treats arrays like enums, ie, making the array objects inherit automatically from a defined array class?
No. Array types implicitly inherit from java.lang.Object
.
Is the array class defined somewhere in such a way that it could be inherited from?
No such class exists. Array types implicitly inherit from Object.
At the JVM spec level, there are a couple of major impediments to making arrays more "class-like":
The "type string" representation of an array type ("[elem-type") only mentions the element. The actual array type has no name, and if it did then the "Lname;" representation is saying that this is a regular class, not an array type.
Arrays are created by special JVM instructions that provide the element type as an operand not the array type.
And beyond that, a JVM implementation is going to assume things about how arrays work in order to implement them efficiently. Even though (according to the JLS) it appears to theoretically possible to use an invoke
instruction to call a non-standard method on an array, a JVM interpreter or JIT compiler wouldn't know what to make of it ... even if you somehow managed to sneak the invoke
past the class loader and verifier.
Once you get past that, then there is that problem that if arrays could be declared with user-defined superclasses, then those superclasses would (presumably) be able to have instance variables. But that implies that the JVM spec needs to change so that:
the heap nodes for arrays can hold instance variables as well as the array itself,
the regular field load and store instructions work on array objects as well as reculare objects,
and so on.
As you can see, this "small extension" unravels a whole lot of other design decisions in the JVM.