在这种情况下,如何避免switch语句

时间:2015-02-28 00:47:06

标签: java oop

我想避免使用switch声明,但我不知道如何。 这是我的问题:

public class Person{
    String status;

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

我想做这样的事情:

    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();
    }   
}

问题是:如果Person吃了一些东西,那么他必须是FullPerson,但如果我有HungryPerson的引用,我怎样才能将其更改为FullPerson

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

3 个答案:

答案 0 :(得分:5)

实际上,从面向对象的角度来看,您的第一个实现更好。对象的状态可以更改,但对象本身仍然是同一个对象。即使你饿了或吃完饭,你仍然是同一个人。您可能希望使用Enum而不是字符串作为状态。

答案 1 :(得分:0)

使用if / else。

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

doSomethingElse();

答案 2 :(得分:0)

而不是使用switch语句,您可以使用if-else。 您可以使用 if(status.equals("饥饿"))来检查此人的状态是否已满,然后根据需要调用相应的方法。

相关问题