0

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.

0

2 Answers 2

4

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.

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."); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

It's like @Chrome but cases instead of instanceof.
0

Add default option in your switch-case block:

 default: .... 

Its complaining because if someVar is not x or y then it doesn't have any return statement.

Alternatively, you can add a default return statement in the end e.g.

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

7 Comments

bad idea the default clause should never be reached.
@RomanC : What do you mean? Even the accepted answer with several votes has the same thing.
@RomanC I am really missing something. If you are returning with switch case, it has to handle/return in all cases. How does compiler know, someVar is only x or y?
they are lazy to think so why they vote or I don't know who voted it was not seen on this site. Don't believe to what has been accepted.
only x or y better mapped to get instances of known types.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.