7

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?

Abhishek Oza
  • 3,072
  • 1
  • 27
  • 35
  • Might be a better question for Programmers SE. Also see my question [here](http://programmers.stackexchange.com/a/239194/87528). – Azar Jul 23 '14 at 14:45
  • 1
    possible duplicate of [Java: Extend class as array](http://stackoverflow.com/questions/10914928/java-extend-class-as-array) – Eran Jul 23 '14 at 14:47
  • because it's a primitive not a class. You could extend from ArrayList instead but you will be having List – Federico Piazza Jul 23 '14 at 14:50
  • 1
    @Eran I don't think so, as that question asks: whether java allows so. Whereas my question is: why Java does not allow this? – Abhishek Oza Jul 23 '14 at 14:54

2 Answers2

13

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.
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • I think the argument that it would allow someone to override the `clone()` method might be invalid. If a method of a superclass is declared as final, then it cannot be overidden in a derived class. – Mitselplik May 01 '16 at 02:12
  • 1
    I get why he wants to do this. I'd like to do the same to add Linq-style code into Java. It is inconvenient that you can't declare an array `Thing[] list = new Thing[100];`, access elements using array syntax 'Thing thisThing = list[50];` and also use extension methods: 'Thing[] subset = list.Where( new Comparator,,, ). And you can't override the [] operator to simplify code either. – Mitselplik May 01 '16 at 02:28
6

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

assylias
  • 310,138
  • 72
  • 642
  • 762