我的项目包含两个类:类型1和类型2是每个类都有自己的功能和字段
我将按以下方式使用它们:
private void initialize(String type) {
if (type == "Type1") {
x = new Type1;
} else if (type == "Type2") {
x = new Type2;
}
}
X变量必须是什么类型?
============================
我使用超类和接口,但无法访问类型1或类型2的变量和方法,而只能访问超类的变量和方法
============================
public class Type1 extends SuperClass{
public int var = 1;
}
public class Type2 extends SuperClass{
public int var = 2;
}
private void initialize(String type) {
switch (type) {
case "Type1":
x = new Type1();
break;
case "Type2":
x = new Type2();
break;
}
}
void main(){
//int num = x.var;
}
在这种情况下不能用于强制转换:((Type1)x).var
解决方法:
如果x是可以同时包含Type1和Type2的变量,则x可以是:
>两者的超类
>两个类都正在实现的接口
例
情况1
public class SuperType{}
public class Type1 extends SuperType{}
public class Type2 extends SuperType{}
那你就可以
private void initialize(String type) {
SuperType x = new Type1();
//or
SuperType x = new Type2();
both are valid
情况二
public interface IType{}
public class Type1 implements IType{}
public class Type2 implements IType{}
那你就可以
private void initialize(String type) {
IType x = new Type1();
//or
IType x = new Type2();
编辑
在1和2的情况下,x都是只能从Supertype或IType调用方法的变量,也许您需要Type1特定的方法,然后需要强制转换
((Type1)x).myType1OnlyMethod ();
标签:java,android
来源: https://codeday.me/bug/20191026/1937679.html