简体   繁体   English

从多个继承的类中返回一个抽象类

[英]Returning an abstract class from multiple inherited classes

I'm trying to do the following: 我正在尝试执行以下操作:

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 is complaining that method must return a type of G. How should I go about returning G1 OR G2 (which both extend G)? Java抱怨方法必须返回G类型。我应该如何返回G1或G2(它们都扩展了G)? It very well may be that I'm approaching this entirely wrong... 很有可能我正在完全犯错...

Thank you. 谢谢。

Your problem is not related to inheritance; 您的问题与继承无关; you must throw an exception or return something of type G in the case where your switch does not fall into case x or case y . 如果您的开关不属于case xcase y必须抛出异常或返回G类型的东西。

For example: 例如:

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.");
    }
 }

Add default option in your switch-case block: 在您的switch-case添加默认选项:

        default: ....

Its complaining because if someVar is not x or y then it doesn't have any return statement. 它的抱怨是因为如果someVar不是xy那么它就没有任何return语句。

Alternatively , you can add a default return statement in the end eg 或者 ,您可以return statement in the end添加默认的return statement in the end例如

  public G method() {
    switch(someVar) {
       case x:
        return new G1();
       case y:
        return new G2();
     }
     return defaultValue; // return default
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM