【发布时间】:2018-05-31 09:35:33
【问题描述】:
考虑到我有很多类,都继承自同一个类:
public class A
{
...
}
public class AA extends A
{
...
}
public class AB extends A
{
...
}
public class AC extends A
{
...
}
然后在代码的其他部分,我想返回一个子类,具体取决于发送到该函数的值,如下所示:
public A getChild(int value, Object foo)
{
switch(value)
{
case 0: {
return new AA(foo);
}
case 1: {
return new AB(foo);
}
case 2: {
return new AC(foo);
}
default: {
return new AA(foo);
}
}
}
在这个例子中,我只有 3 种类型的孩子。但我可以假设其中有 30 个,switch 声明会变得很大。
有没有什么方法可以使用 switch 语句之外的其他东西来做同样的事情,而且会更通用?像 C 中的函数指针一样?
【问题讨论】:
-
好吧,您不会遇到类似
if-else行为的部分,因为您必须决定返回哪个value哪种类型的实例
标签: java inheritance switch-statement generic-programming