我想获取子类的实例,但我总是得到父类实例,有人可以解释我为什么吗?根据 XMLType ID,我正在获取子类实例(字符串或任何 URI)等,但在某些情况下我需要子类实例。
代码::
public abstract class WSType
public final static WSType getInstance(int xmlTypeId) {
switch (xmlTypeId) {
case STRING: return WSStringType2.getInstance(); //**here i am always getting Parent class but i am calling instance of WSStringType2.**
case ANYURI: return WSAnyURIType2.getInstance();
}
}
public final static WSType getInstance(int xmlTypeId, String data) throws XCallException {
WSType wsData = WSType.getInstance(xmlTypeId); /**/calling happening Here**
}
}
public class WSStringType extends WSType {
protected String m_data;
public WSStringType() { m_data = "'"; }
public WSStringType(String name){ m_data=name; }
public static WSStringType getInstance() {
return new WSStringType();
}
}
class WSStringType2 extends WSStringType {
public WSStringType2() { m_data = "'"; }
public static WSStringType2 getInstance() {
return new WSStringType2();
}
public WSStringType2(String newValue){
super(newValue);
}
}
最佳答案
getInstance(int xmlTypeId)
的返回类型是 WSType
,它是父级。您可以简单地将其转换为 WSStringType2
,因为 WSStringType2
扩展了 WSStringType
且 WSStringType
扩展了 WSType
WSType wt = WSType.getInstance(STRING);
WSStringType2 wt2 = null;
if (t instanceof WSStringType2) {
wt2 = (WSStringType2) wt;
}
关于java - 我总是得到父类的实例。但我需要一个子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27019444/