我的問題很簡單,但我無法弄清楚如何實現我想要的。我想實現一個方法,根據給定的參數,返回一個子類或另一個(我明白,我可以有一些類中的這種行爲,使開發更面向對象,但我仍然在學習)。返回子類
所以我想到了這個解決方案,但它不能編譯。
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