2014-10-04 58 views
2

我的問題很簡單,但我無法弄清楚如何實現我想要的。我想實現一個方法,根據給定的參數,返回一個子類或另一個(我明白,我可以有一些類中的這種行爲,使開發更面向對象,但我仍然在學習)。返回子類

所以我想到了這個解決方案,但它不能編譯。

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; 
} 
+0

什麼是錯誤?請發佈完整的編譯器錯誤。 – 2014-10-04 19:40:01

+0

泛型在這裏沒有用處,它們在程序執行期間不存在(當'input'被評估時)。 – Radiodef 2014-10-04 19:41:58

+0

你的方法沒有得到返回類型。 – 2014-10-04 19:42:30

回答

2

首先,你需要從你的類定義中的括號去掉(()):

public abstract class A { 
    //some code 
} 

public class B extends A { 
    //some code 
} 

public class C extends A { 
    //some code 
} 

其次,getObject應該原封不動地返回A

public static A getObject(String input){ 
    if(input.indexOf("b") != -1){ 
     return new B(); 
    } 
    if(input.indexOf("c") != -1){ 
     return new C(); 
    } 
    return null; 
} 
+0

非常感謝,它比我想象的要簡單得多。 關於。 – Leandro 2014-10-04 20:13:58

1

在你的例子中,我沒有看到任何需要使用泛型。你的方法可以簡單地返回A

public static A getObject(String input){ 
    if(input.indexOf("b") != -1){ 
     return new B(); 
    } 
    if(input.indexOf("c") != -1){ 
     return new C();  
    } 
    return null; 
}