我有一个类钱包,它扩展到3个不同的钱包PaypalWallet,BankWallet和ChequeWallet。每个具有不同属性的都保存超类属性。
这些钱包用于Payout,它可以扩展2笔付款,PaymentBank和PayoutCheque。
public class Payout {
@Id private String id;
private String userId;
protected Wallet userWalletInfo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Wallet getUserWalletInfo() {
return userWalletInfo;
}
public void setUserWalletInfo(Wallet userWalletInfo) {
this.userWalletInfo = userWalletInfo;
}
}
如果我在ChequePayout中继承了这个类,我如何指定userWalletInfo应该是ChequeWallet的一个实例?类似于扩展课程?
我的第一个念头是覆盖了setter,就像这样:
public class PayoutCheque extends Payout {
private String serialNumber;
private ChequeStatus status;
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public ChequeStatus getStatus() {
return status;
}
public void setStatus(ChequeStatus status) {
this.status = status;
}
@Override
public void setUserWalletInfo(Wallet userWalletInfo) {
if (userWalletInfo instanceof ChequeWallet) {
super.setUserWalletInfo(userWalletInfo);
}
else {
//throw exception
}
}
}
然而,我觉得这不是正确的做法,或者我错过了一些重要的事情。
答案 0 :(得分:1)
听起来你正在寻找泛型。
private class Wallet {
}
private class ChequeStatus {
}
private class ChequeWallet extends Wallet {
}
public class Payout<W extends Wallet> {
private String id;
private String userId;
protected W userWalletInfo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Wallet getUserWalletInfo() {
return userWalletInfo;
}
public void setUserWalletInfo(W userWalletInfo) {
this.userWalletInfo = userWalletInfo;
}
}
public class PayoutCheque extends Payout<ChequeWallet> {
private String serialNumber;
private ChequeStatus status;
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public ChequeStatus getStatus() {
return status;
}
public void setStatus(ChequeStatus status) {
this.status = status;
}
@Override
public void setUserWalletInfo(ChequeWallet userWalletInfo) {
super.setUserWalletInfo(userWalletInfo);
}
}
答案 1 :(得分:0)
if(userWalletInfo.getClass().equals(ChequeWallet.class)){
}