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
DEF
needs to extendABC
- I mean, is aDEF
logically aABC
? Inheritance is powerful but needs to be used with caution.In your case, I'd rather have:
And have both
ABC
andDEF
implementingWithVariable
. This way constructing aABC
object will initialise the needed variable, and constructing aDEF
object won't do anything, but they'll both reply to the same message (getVariable()
).