I have a super class that has this constructor:
public Super(String p){
String[] result = p.split(",");
setA(result[0]);
setB(result[1]);
setC(result[2]);
setD(result[3]);
setE(result[4]);
}
Then I have a subclass, where I want to use the same constructor, but add 2 more strings. This is my code:
public Sub(String d){
super(d);
setF(result[5]);
setG(result[6]);
}
Using this code I get an error that result is not specified. How can I fix this?
Basically you'd need to do the split again in the subclass constructor - the local variable result
isn't available in the subclass constructor:
public Sub(String d){
super(d);
String[] result = d.split(",");
setF(result[5]);
setG(result[6]);
}
Yes, it'll end up duplicating work, but that's somewhat hard to avoid. You could do so by having a private subclass constructor which takes a String[]
, and a factory method to do the split first:
protected Super(String[] result) {
setA(result[0]);
setB(result[1]);
setC(result[2]);
setD(result[3]);
setE(result[4]);
}
protected Super(String d) {
this(d.split(","));
}
...
private Sub(String[] result) {
super(result);
setF(result[5]);
setG(result[6]);
}
public static Sub fromString(String d) {
return new Sub(d.split(","));
}
There's an alternative option where the superclass constructor calls a virtual method which is overridden in the subclass, but that's really fragile and it sufficiently horrible that I'm not even going to provide an example.
See more on this question at Stackoverflow