Home > database >  Try to use and implement array by its reference in childclass but it stays null [duplicate]
Try to use and implement array by its reference in childclass but it stays null [duplicate]

Time:09-18

For a project in Java I want to create a private reference to an array in a superclass, but do not implement it. I want to do the implementation in the childclass, so I created a getter method for that array in the superclass. In the childclasses constructor, I implement the array and now the problem is, that the array reference in the superclass stays null even if I added an array to the reference. I want to use the array later in the superclass. I will add some code for better understanding.

I understand my fault that this is not easily possible in Java like this, but is there any solution to "edit" the array like this by it's reference or do I have to do this with a setter method?

//parent class
public abstract class Superclass {
    private Test[] test_Values;
    
    public Measurement[] getTestValues() {
        return this.test_Values;
    }
}

//child class
public class ChildClass extends SuperClass {

    public ChildClass() {
        Test[] measures = super.getTestValues();
        measures = new Test[4];
    }
}

CodePudding user response:

Initialize your array in the parent constructor:

public abstract class Superclass {
    private Test[] test_Values;

    protected Superclass(int capacity) {
        this.test_Values = new Test[capacity];
    }

    public Test[] getTestValues() {
        return this.test_Values;
    }
}

Then, you have to use that non-default constructor in your child classes.

public class ChildClass extends SuperClass {

    public ChildClass() {
        super(4);
    }
}

Or, to get additional control over how you initialize the values in the array, you could add an abstract method that is used in the parent's constructor:

public abstract class Superclass {
    private Test[] test_Values;

    protected Superclass() {
        this.test_Values = initializeArray();
    }

    public Test[] getTestValues() {
        return this.test_Values;
    }

    protected abstract Test[] initializeArray();
}

The child class then needs to implement that abstract method:

public class ChildClass extends SuperClass {
    @Override
    protected Test[] initializeArray() {
        Test[] testValues = new Test[4];
        // calculate elements
        return testValues;
}
  • Related