我的问题很简单,但我不知道如何实现我想要的。
我想实现一种方法,根据给定的参数,返回一个子类或另一个子类(我知道我可以在某个类中具有这种行为,以使开发更加面向对象,但我仍在学习) .
所以我想到了这个解决方案,但它无法编译。
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;
}
最佳答案
首先,您需要从类定义中删除括号 (()
):
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;
}
关于java - 返回子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196444/