efnx
efnx

Reputation: 73

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)? It very well may be that I'm approaching this entirely wrong...

Thank you.

Upvotes: 0

Views: 75

Answers (2)

Yogendra Singh
Yogendra Singh

Reputation: 34367

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
  }

Upvotes: 0

Jon Newmuis
Jon Newmuis

Reputation: 26502

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

Upvotes: 4

Related Questions