Search code examples
javaoopabstract-class

Referencing instance variables from within abstract class


I have an abstract class which lays out what each of its subclasses should implement. Most methods will have different implementations for each subclass, but some will be the same for all. I want the methods that will be the same to be to be defined in the abstract class, so that I'm not pasting the same method into several different classes. However, when I call that method on an instance of the abstract's subclass, I receive a nullpointer because, I imagine, the method implemented in the abstract class is referencing the abstract's field, not the instance's field.

Can someone point out where the flaw is?

For example:

abstract class ControlView {
    String[] controls;

    abstract void render();

    void release() {
        for (int i = 0; i <= controls.length; i++) {
            //Release the controls
        }
    }
}



class StartingControls extends ControlView{

    String[] controls;
    Button uiDrawButton;
    Button uiLoadButton;


    StartingControls() {
        this.controls = new String[2];

        uiDrawButton = new Button();
        this.controls[0] = uiDrawButton;

        uiLoadButton = new Button();
        this.controls[1] = uiLoadButton;
    }


    public void render() {
        //Unique Render implementation
    
    } 
}

When I call

instanceOfStartingControls.release();

I obviously want to iterate over the two strings that I put into instanceOfStartingControls' controls field when it was constructed. I do not want to iterate over the non-initialized array that is apparently living in the abstract.

Is it some combination of access modifiers or static methods that is keeping this from working as it seems it should, or am I missing some crucial bit of knowledge on abstract classes? This feels like a basic question, but I'm having a hard time putting it to words, so I've not been satisfied with any results from my searches.


Solution

  • There are two arrays called controls. The one in the derived class is obscuring the one in the base class, thus the base instance never gets set non-null.

    Delete the declaration from the derived class.

    This issue is not related to the base being abstract. If you use the same field name in a derived class as is used in a base class, the base instance will be obscured.