0

Say I have an Abstract generic class:

public abstract class QuestionObject<T extends Answerable<?>> {   
    public abstract T returnAnswerable();
    public abstract void renderQuestionLayout(T answer);
}

and a companion generic class to go with it:

public interface Answerable<T> {
...
}

I have a bunch of subclasses that extend QuestionObject and have their own particular Answerable. So for example, a TrueFalseQuestion would be declared with a TrueFalseAnswer:

public class TrueFalseQuestion extends QuestionObject<TrueFalseAnswer> {
...
}

Let's saw I want to call the method renderQuestionLayout at the QuestionObject level. Is that possible? Something like:

QuestionObject<?> q = getCurrentQuestion();
Answerable<?>a = getAnswer();
q.renderQuestionLayout(a);

doesn't work.

0

1 Answer 1

1

Look at your last code snippet:

QuestionObject<?> q = getCurrentQuestion();
Answerable<?>a = getAnswer();
q.renderQuestionLayout(a);

The ? wildcard does not help the compiler determine which version of renderQuestionLayout to call. Right now, q is an instance your abstract parent class where the method has an abstract declaration.

You'll need to explicitly cast to the appropriate subclass type, or rethink your design a little bit so you don't have casts everywhere :p

Sign up to request clarification or add additional context in comments.

2 Comments

I figured this might be the answer (explicitly casting). Do you think this is an example of bad design? What would a redesign look like? Thx.
Well, if you have too many subclasses, doing the casts everywhere can get pretty nasty. My suggestion would be to use a factory of some kind to get instances of the particular subclass that you need.

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.