Question

class ABC {
    private int[] variable;
    public int[] getVariable() {
        return variable;
    }
    public ABC() {
        variable = new int[123456];
    }
}

class DEF extends ABC {
    public int[] getVariable() {
        return new int[0];
    }
} 

variable is used in ABC, but completely unused and needless in DEF. But I can't see any proper way to prevent creating this big array in DEF, because always some constructor of superclass has to be executed. I see only one, inelegant way: new, "fake" constructor for ABC:

protected ABC(boolean whatever) {}

Then in DEF I can write:

public DEF() {
    super(true);
}

and it works - variable isn't initialized.

But, my question is - can I solve this more properly?

Maybe if variable is unused, compiler automatically deletes her? It's quite often situation, when such feature could be useful.

Was it helpful?

Solution

Are you sure DEF needs to extend ABC - I mean, is a DEF logically a ABC? Inheritance is powerful but needs to be used with caution.

In your case, I'd rather have:

public interface WithVariable {
  int[] getVariable();
}

And have both ABC and DEF implementing WithVariable. This way constructing a ABC object will initialise the needed variable, and constructing a DEF object won't do anything, but they'll both reply to the same message (getVariable()).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top