Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

How to replace if else statement with switch statement

Hi I am in a situation where I need to use multiple else if's and I would like to use switch statements, I have tried a lot but I am not able to do so. How can I convert the following else if's to switch?

public ApiObservables(Object o) {
        if (o instanceof SitesController) {
            mSitesApi = getSitesApi();
        } else if (o instanceof QuestionController) {
            mQuestionApi = getQuestionApi();
        } //more else if's
    }

I would like to do something like this:

public ApiObservables(Object o) {
        switch (o) {

        }
    }

Upvotes: 0

Views: 2187

Answers (4)

marcellorvalle
marcellorvalle

Reputation: 1679

I don't know if you can refactor your code but What about a diffetent approach using interfaces? Something like this:

interface API {
   //method signatures here
}

class SitesApi implements API {
    //implementation here
}

class QuestionApi implements API {
    //implementation here
}

interface Controller {
    API getAPI();
}

class QuestionController implements Controller {
    @Override
    public API getAPI() {
        return new QuestionAPI();
    }
}

class SitesController implements Controller {
    @Override
    public API getAPI() {
        return new SitesAPI();
    }
}

Then:

public ApiObservables(Controller controller) {
    someApi = controller.getAPI();
}

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 152

    I don't know about your remaining code try this by passing in this function repective controller string as per your object

    and if you use object in switch case then i think it will not support

try this one

        public ApiObservables(String o) {
            switch(o) {
            case "SitesController":
               mSitesApi = getSitesApi();
               break;

             case "QuestionController":
            mQuestionApi = getQuestionApi();

             default:
               System.out.println("place any thing that you want to show any message");
               break;
            }
        }

Upvotes: 0

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

In your situation, I would use method overloading :

public ApiObservables foo(Object o) {
  //throw new IllegalArgumentException?
}

public ApiObservables foo(SitesController o) {
  return getSitesApi();
}

public ApiObservables foo(QuestionController o) {
  return getQuestionApi();
}

Upvotes: 1

dryairship
dryairship

Reputation: 6077

  • When using switch case, the control variable must be of primitive type, or String, or enum. You cannot use objects in switch-case. From JLS:

    The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type

  • The switch case only checks for equality ( i.e., similar to using == operator). So, you cannot use instanceof in switch-case

Upvotes: 2

Related Questions