So if I have a method where a variable can be an instance of a bunch of different classes where only some of them have a specific instance variable, how do I use this instance variable in the method without getting the cannot be resolved or is not a field
error?
consider this code:
void method1(){
SuperType randomInstance = getRandomInstance();
if(randomInstance.stop == true) //do something
}
where SuperType
is a super class to all possible instances that randomInstance
can hold.
However, an instance doesn't necessarily have the variable stop
so I get an error saying stop cannot be resolved or is not a field
So my question is, is there a way to get around this or would I have to create different methods for different instances depending on if they have the variable stop
or not?
If having a
stop
property can be viewed as a behavior shared by some of the sub-classes ofSuperType
, you can consider defining an interface - let's call itStoppable
- having methodsgetStop
(or perhapsisStopped
if it's a boolean) andsetStop
.Then your code can look like :