问题
As an experiment, I tried to extend an int
-array like this:
public class IntArrayExtension extends int[]{
// additional fields and methods.
}
to add some methods related to sorting, swapping, sub-array building etc. in the class itself. But I got this error while compiling:
IntArrayExtension.java:1: unexpected type
found : int[]
required: class
public class IntArrayExtension extends int[]{
^
1 error
I am curious to know: why Java does not allow to extend an array?
回答1:
Extending a fundamental type such as a String
or an array opens up security holes. If Java let you extend an array, its methods that take arrays would become insecure. That is why strings are final
, and arrays cannot be extended at all.
For example, you could override the clone()
method, and return an array of incorrect size. This has a potential of breaking the logic of system code that takes an array as its parameter.
On top of that, arrays are special objects in Java, in that they do not have a class definition.
There are two solution to the problem that you are trying to solve:
- You could put the logic into a helper class with static methods, similar to
Collections
, etc. or - You could encapsulate an array inside your
IntArrayExtension
class, and provide wrapper methods for accessing the array and its additional features.
回答2:
Arrays are objects but an array type is not a class and therefore can't be extended. See for example JLS #10.8.
来源:https://stackoverflow.com/questions/24913612/why-java-does-not-allow-to-extend-array-type