为了账号安全,请及时绑定邮箱和手机立即绑定

java方法可以返回不同的对象吗?

java方法可以返回不同的对象吗?

潇潇雨雨 2024-01-17 20:53:15
假设我有两个类 Person1 和 Person2,它们实现了 History 接口。我想在 History 接口中有一个静态方法,它根据如下字符串返回 Person1 或 Person2 :public static Object getPerson(String p){    switch(p){        case "a":            return new Person1();        default:            return new Person2();    }}我这里没有任何错误。但是如何在另一个类中使用它,以便从 Person1 或 Person2 获取方法?我尝试这样做:Object env = IEnvironment.getPerson(clientEnv);但我不能写 env.myMethod() 例如。接口是正确的解决方案吗?如何实现这一目标?谢谢!
查看完整描述

2 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

您可以创建一个接口并让这些类实现这个接口。然后从 switch 就可以返回这个接口。


 public static History getPerson(String p){

    switch(p){

        case "a":

            return new Person1();

        default:

            return new Person2();

    }

 }


查看完整回答
反对 回复 2024-01-17
?
慕虎7371278

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 而不是 == 。)


查看完整回答
反对 回复 2024-01-17
  • 2 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信