2

我有一个具有此构造函数的超类:

public Super(String p){
    String[] result = p.split(",");
    setA(result[0]);
    setB(result[1]);
    setC(result[2]);
    setD(result[3]);
    setE(result[4]);
}

然后我有一个子类,我想在其中使用相同的构造函数,但还要添加 2 个字符串。这是我的代码:

public Sub(String d){
    super(d);
    setF(result[5]);
    setG(result[6]);
}

使用此代码,我收到未指定结果的错误。我怎样才能解决这个问题?

4

1 回答 1

3

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.

于 2015-03-18T19:47:20.800 回答