2 回答
TA贡献1712条经验 获得超3个赞
您可以创建一个接口并让这些类实现这个接口。然后从 switch 就可以返回这个接口。
public static History getPerson(String p){
switch(p){
case "a":
return new Person1();
default:
return new Person2();
}
}
TA贡献1802条经验 获得超4个赞
你想要这样的东西吗:
$ java Foo a
Person1
$ java Foo b
Person2
$ cat Foo.java
/**
* This is just a container so I can do it all in one class.
*/
public class Foo {
// Static just for packaging purposes
public static class History {
public void printMe() { System.out.println("History"); }
}
// Static just for packaging purposes
public static class Person1 extends History {
public void printMe() { System.out.println("Person1"); }
}
// Static just for packaging purposes
public static class Person2 extends History {
public void printMe() { System.out.println("Person2"); }
}
public static History makePerson(String str) {
History retVal = (str.equals("a")) ? new Person1() : new Person2();
return retVal;
}
public static void main(String[] args) {
History person = makePerson(args[0]);
person.printMe();
}
}
(编辑以测试它并在比较中正确使用 .equals 而不是 == 。)
添加回答
举报