我想得到一个子类的实例,但我总是得到父类实例可以任何人解释我为什么?根据XMLType ID我得到了孩子的实例(字符串或anyURI)等。但在某些情况下我需要子类实例。
代码::
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);
}
}
答案 0 :(得分:2)
getInstance(int xmlTypeId)
的返回类型是WSType
,它是父项。您可以简单地将其投放到WSStringType2
,因为WSStringType2
延伸WSStringType
而WSStringType
延伸WSType
WSType wt = WSType.getInstance(STRING);
WSStringType2 wt2 = null;
if (t instanceof WSStringType2) {
wt2 = (WSStringType2) wt;
}