0

I am initializing an Object(Bateau), which contains within it an array of objects (Element) called elements.

Upon calling the constructor, I want to create several elements for a "bateau" object.

The number of elements vary depending on which kind of "bateau" it is because "Bateau" has 3 sub-classes which determine the number of elements to initialize.

I get a NPE when I try to add a new Element to elements, can anyone help me resolve this issue ?

public class Bateau {
private boolean horizontal = false;
protected Element[] elements;

public Bateau(int pX, int pY, boolean horizontal, int nombreElements) {
    this.horizontal = horizontal;
    for (int i = 0; i < nombreElements; i++) {
        if (this.horizontal) {
            //NullPointerException elements[i] not initialized ?
            this.elements[i] = new Element((pX + i), pY);
        } else {
            this.elements[i] = new Element(pX, (pY + i));

        }
    }
}}
3
  • 2
    where do you think the array initialization occurs? some reading: stackoverflow.com/questions/25761646/… Commented Jan 30, 2015 at 16:28
  • I added: elements = new Element[nombreElements]; in my constructor. Commented Jan 30, 2015 at 16:31
  • Also stackoverflow.com/q/27180473/573032 Commented Jan 30, 2015 at 16:38

1 Answer 1

4

In your debugger you would be able to see that

Element[] elements = null;

I suggest you initialise it with

elements = new Element[nombreElements];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.