简体   繁体   中英

How can I avoid switch statement in this case

I want to avoid using a switch statement but I don't know how. This is my problem:

public class Person{
    String status;

    public void doSomething(){
        switch (status) {
        case "hungry":
                eatSomething();
                status = "full";
            break;
        case "full":
                doNothing();
                status = "hungry";
        default:
            break;
        }
    }}

I want to do something like this:

    public abstract class Person{
        public abstract void doSomething();
}

public class HungryPerson extends Person{
        @Override
        public void doSomethink() {
            eatSomething();
        }
}


public class FullPerson extends Person{
    @Override
    public void doSomething() {
            doNothing();
    }   
}

The problem is: if the Person ate something then he has to be FullPerson , but if I had a reference with HungryPerson how can I change it to FullPerson ?

int main(){
    Person person = new HungryPerson();
    person.doSomething();
    //I want to person contain a FullPerson reference.
}

Actually, your first implementation is better from an Object Oriented point of view. The state of the object can change but the object itself is still the same object. You remain the same person even when you are hungry or after you eat. You might want to use an Enum instead of a String for the status.

use an if/else.

if(status == "hungry")
     doSomething();

doSomethingElse();

instead of using the switch statement, you can use if-else. you can use if(status.equals("hungry")) to check if the status of the person is hungry or not and then call the respective methods as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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