Java: Extend class as array
Asked Answered
P

1

4

Quick novice question: I want to extend a class as an array, like so

public class Map extends Item[][]
{

}

Is this possible, am I going about it the wrong way? Thanks!

Perchance answered 6/6, 2012 at 13:13 Comment(3)
I guess in your case could be better Composition, instead of Inheritance...Anglim
I would take a look at the Collections API as there may already be the type of class you are looking for. Also, this would allow you to correctly use interfaces in your code (e.g. Map). If not then favour composition over inheritance and have your class have a property that is the internal array storage.Datcha
What purpose could extending it as an "array" serve that extending it regularly from Item doesn't?Decolorize
M
13

Arrays are weird beasts. The have some properties, like length but they are not a class, so you can't extend them like you are attempting.

I think you are better off using composition, i.e. create a class that contains an Item[][] and then extend that class (if you need to, having one class might be enough)

Metathesis answered 6/6, 2012 at 13:15 Comment(3)
Alternatively you can extend List, e.g. ArrayList. But composition is definitely better.Milagrosmilam
@Milagrosmilam yes, if he really wants a collection. I'm assuming he wants an array. I try to avoid automatically thinking "use a collection" whenever I see an array.Metathesis
I have a similar question: if class '''Map extends Item[]''' is not allowed why is '''List<? extends Item[]>''' allowed and what is the type of this list? @MetathesisStatistical

© 2022 - 2024 — McMap. All rights reserved.