[英]Cast inherited variable to subclass
I have two closely knit cluster of classes. 我有两个紧密联系的班级。 For the sake of explanation, lets call one the view
and the other the template
. 为了说明起见,让我们一个称为view
,另一个称为template
。 The template
tells the view
how to look. template
告诉view
外观。 I have a base view
and base template
class and a number of paired subclasses of them. 我有一个基本view
和基本template
类,以及它们的许多成对的子类。
So, like so: 所以,像这样:
Base Classes 基类
BaseTemplate <-> BaseView BaseTemplate <-> BaseView
Subclasses 子类
TemplateA <-> ViewA TemplateA <-> ViewA
TemplateB <-> ViewB TemplateB <-> ViewB
TemplateC <-> ViewC TemplateC <-> ViewC
TemplateD <-> ViewD TemplateD <-> ViewD
The view
s (Even the base view
) each have a template
, of the corresponding type, as a variable. 每个view
(甚至是基本view
)都有一个对应类型的template
作为变量。 How can I cast, for example, the variable of BaseTemplate
, declared in BaseView
, to TemplateB
, declared in ViewB
? 我怎样才能投,例如,可变BaseTemplate
,在宣布BaseView
,以TemplateB
,在宣布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. 我希望能够在BaseTemplate
设置变量信息,而不必在所有模板子类中设置通用信息。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.