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!

3
  • I guess in your case could be better Composition, instead of Inheritance... Commented Jun 6, 2012 at 13:15
  • 1
    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. Commented Jun 6, 2012 at 13:15
  • 1
    What purpose could extending it as an "array" serve that extending it regularly from Item doesn't? Commented Jun 6, 2012 at 13:16

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively you can extend List, e.g. ArrayList. But composition is definitely better.
@AlexR 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.
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? @hvgotcodes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.