1

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?

0

3 Answers 3

2

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Aah that was actually exactly what I was looking for, I knew I had read about this somewhere!
1

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.)

2 Comments

Well yes they have a supertype but it is not something that I can change since I am using a framework. But I will just create a mutual interface, it will work fine.
@PandaDeTapas: Yup, there you go. Adding an interface of your own with this in it is Eran's answer, I believe.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.