我想使用多态,使基于它的类对象的不同处理动态多态调用,如下所示:强制执行与一般的父类型的输入参数
public class GeneralStuff {
private int ID;
}
public class IntStuff extends GeneralStuff {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
}
public class DoubleStuff extends GeneralStuff {
private double value;
public void setValue(double v)
{
value = v;
}
public double getValue()
{
return value;
}
}
public class ProcessStuff {
public String process(GeneralStuff gS)
{
return doProcess(gS);
}
private String doProcess(IntStuff i)
{
return String.format("%d", i.getValue());
}
private String doProcess(DoubleStuff d)
{
return String.format("%f", d.getValue());
}
}
public class Test {
public static void main(String[] args)
{
IntStuff iS = new IntStuff();
DoubleStuff dS = new DoubleStuff();
ProcessStuff pS = new ProcessStuff();
iS.setValue(5);
dS.setValue(23.2);
System.out.println(pS.process(iS));
System.out.println(pS.process(dS));
}
}
然而,这是不行的,因为调用doProcess(gS)
预计为署名doProcess(GeneralStuff gS)
的方法。
我知道在ProcessStuff
类中我只能有两个暴露的多态处理方法,但实际情况不会允许它,因为我在现有库机制的约束下工作;这只是一个人为测试的例子。
我当然可以,定义process(GeneralStuff gS)
为
public String process(GeneralStuff gS)
{
if (gS instanceof IntStuff)
{
return doProcess((IntStuff) gS);
}
else if (gS instanceof DoubleStuff)
{
return doProcess((DoubleStuff) gS);
}
return "";
}
它的工作原理,但似乎我不应该这样做(加,编程警方会串烧我要以这种方式使用的instanceof )。
有没有办法,我可以强制执行以更好的方式多态调用的方法吗?
在此先感谢您的帮助。
在实际应用中,参数对象('IntStuff','DoubleStuff')被打包为'GeneralStuff'的实例到'Bundle'对象中,并传递给另一个对象('ProcessStuff')对象进行处理,其中参数对象被抽出并根据它们的实际类型采取不同的动作。因此,我实际上没有在直接调用ProcessStuff中提供重载的过程方法的选项(由@βнɛƨнǤʋяʋиɢ建议),并且将'process'方法移入'GeneralStuff'也可能不是一个选项由你和@codegrabber建议)。 – 2012-01-04 06:35:47