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 而不是 == 。)
添加回答
舉報