我的问题很简单,但我无法弄清楚如何实现我想要的。我想实现一个方法,根据给定的参数,返回一个子类或另一个(我明白,我可以有一些类中的这种行为,使开发更面向对象,但我仍然在学习)。返回子类
所以我想到了这个解决方案,但它不能编译。
public abstract class A(){
//some code
}
public class B extends A(){
//some code
}
public class c extends A(){
//some code
}
public static void main(String[] args) {
System.out.println("input: ");
Scanner console = new Scanner(System.in);
String input=console.nextLine();
A myObject = getObject(input);
}
public static <? extends A> getObject(String input){
if(input.indexOf("b") != -1){
return new B();
}
if(input.indexOf("c") != -1){
return new C();
}
return null;
}
什么是错误?请发布完整的编译器错误。 – 2014-10-04 19:40:01
泛型在这里没有用处,它们在程序执行期间不存在(当'input'被评估时)。 – Radiodef 2014-10-04 19:41:58
你的方法没有得到返回类型。 – 2014-10-04 19:42:30