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.
Are you sure
DEFneeds to extendABC- I mean, is aDEFlogically aABC? Inheritance is powerful but needs to be used with caution.In your case, I'd rather have:
And have both
ABCandDEFimplementingWithVariable. This way constructing aABCobject will initialise the needed variable, and constructing aDEFobject won't do anything, but they'll both reply to the same message (getVariable()).