2014-10-04 76 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; 
}