Reputation: 11084
I have two closely knit cluster of classes. For the sake of explanation, lets call one the view
and the other the template
. The template
tells the view
how to look. I have a base view
and base template
class and a number of paired subclasses of them.
So, like so:
Base Classes
BaseTemplate <-> BaseView
Subclasses
TemplateA <-> ViewA
TemplateB <-> ViewB
TemplateC <-> ViewC
TemplateD <-> ViewD
The view
s (Even the base view
) each have a template
, of the corresponding type, as a variable. How can I cast, for example, the variable of BaseTemplate
, declared in BaseView
, to TemplateB
, declared in ViewB
? I would like to be able to set variable information in the BaseTemplate
, rather than having to set generic information in all the template subclasses.
Upvotes: 1
Views: 275
Reputation: 55233
It sounds like you could use generics to address this issue. For example:
public abstract class BaseView<T extends BaseTemplate> {
private final T template;
protected BaseView(T template) {
this.template = template;
}
//common view methods operating using T etc.
}
public final class ViewA extends BaseView<TemplateA> {
public ViewA() {
super(new TemplateA()); //or wherever templates come from
}
// ViewA specific stuff
}
Upvotes: 1