因此,如果我有一个方法,其中变量可以是一堆不同类的实例,而其中只有一些类具有特定的实例变量,那么如何在方法中使用该实例变量而又不会出现cannot be resolved or is not a field错误?

考虑以下代码:

void method1(){
    SuperType randomInstance = getRandomInstance();
    if(randomInstance.stop == true) //do something
}


其中,SuperTyperandomInstance可以容纳的所有可能实例的超类。

但是,实例不一定具有变量stop,所以我收到一条错误消息,提示stop cannot be resolved or is not a field

所以我的问题是,是否有一种解决方法,还是我必须根据实例是否具有变量stop为不同的实例创建不同的方法?

最佳答案

如果可以将具有stop属性视为由SuperType的某些子类共享的行为,则可以考虑定义一个接口-我们称其为Stoppable-具有方法getStop(或者可能是(如果是布尔值)和isStopped

然后您的代码如下所示:

void method1(){
    SuperType randomInstance = getRandomInstance();
    if (randomInstance instanceof Stoppable) {
        Stoppable sInstance = (Stoppable) randomInstance;
        if(sInstance.getStop() == ...) //do something
    }
}

10-06 07:27
查看更多