0

我正在尝试执行以下操作:

abstract class G {
    protected var = 0;
}

class G1 extends G {
    var = 1;
}

class G2 extends G {
    var = 2;
}

// This is where I'm having a problem
public G method() {
    switch(someVar) {
        case x:
            return new G1();
        case y:
            return new G2();
    }
 }

Java 抱怨该方法必须返回 G 类型。我应该如何返回 G1 或 G2(它们都扩展了 G)?很可能我正在接近这个完全错误的......

谢谢你。

4

2 回答 2

4

您的问题与继承无关;G在您的开关不属于case xor的情况下,您必须抛出异常或返回某种类型的东西case y

例如:

public G method() {
    switch(someVar) {
        case x:
            return new G1();
        case y:
            return new G2();
        default:
            // You can return null or a default instance of type G here as well.
            throw new UnsupportedOperationException("cases other than x or y are not supported.");
    }
 }
于 2012-10-21T20:42:33.133 回答
0

switch-case在您的块中添加默认选项:

        default: ....

它抱怨是因为 if someVaris notx或者ythen 它没有任何 return 声明。

或者,您可以添加一个默认值,return statement in the end 例如

  public G method() {
    switch(someVar) {
       case x:
        return new G1();
       case y:
        return new G2();
     }
     return defaultValue; // return default
  }
于 2012-10-21T20:46:36.417 回答