简体   繁体   中英

Why Java does not allow to extend array type

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?

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.

Arrays are objects but an array type is not a class and therefore can't be extended. See for example JLS #10.8 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM