handle different instance variables in method

93 views Asked by At

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?

3

There are 3 answers

1
Eran On BEST ANSWER

If having a stop property can be viewed as a behavior shared by some of the sub-classes of SuperType, you can consider defining an interface - let's call it Stoppable - having methods getStop (or perhaps isStopped if it's a boolean) and setStop.

Then your code can look like :

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

Give the classes in question a common supertype or interface (they seem, from your code, to have one — SuperType), and define the instance field (it's not a "variable") on the supertype or define a getter function on the interface. (Actually, even if the supertype is a class, it's commonly best practice to define the field using a getter anyway, even if you could make it a public or protected instance field.)

0
Giovanni On

If you cannot change your class hiearchy with the introdution of an Interface (Stoppable for example) can resort to reflection to detect if the class has a provate field named stop.

You can find an example of field "listing" from a class here and Field is documented here