java的类的复制_如何在Java中复制类

我的项目包含两个类:类型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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值