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)? 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
Gin the case where your switch does not fall intocase xorcase y.For example: