java - 在方法中返回 Java 子级

标签 java

鉴于以下类,我决定基于 if/else 语句创建子类,这是正确的方法吗?另外,声明一个返回父级然后返回子级的方法是否正确? (参见一些方法)。好像不对,有更好的办法吗?

public class Parent {

    int someInt;
}

public class Child1 extends Parent {

    int id1;
    String field1;
}

public class Child2 extends Parent {

    int id2;
    String field2;
}

这些类的使用方式如下:

public class SomeClass {

    public Parent someMethod(int option) {

         Parent object = null;
         if (option == 1) { 
            object = new Child1();
            // set Child1 fields
            return object;
         }
         else {
             object = new Child2();
            // set Child2 fields
            return object;
        }

    }


}

最佳答案

is it correct to declare a method that returns Parent and then return a child?

是的,Parent 将是此方法的正确返回类型。代码看起来没问题。

一些小评论:

  • 您可以将其实现为 return option == 1 吗? new Child1() : new Child2();
  • 类并没有真正的“父/子”关系。认为是一个。 (你会说 child parent 吗?)在我看来,基类(或父类(super class))与子类是更好的术语。

关于java - 在方法中返回 Java 子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618082/

相关文章:

java - 单击选定的复选框

java - 如何使用带有辅助注入(inject)的模拟对象而不是真正的实现类

java - Jolt 变换未命名数组

java - 无法在远程HBase表中插入记录

java - 如何使用 Camel 邮件调整imap的轮询频率

java - Spring OAuth oauth/token 在 tomcat 上返回 404 war

java - 让break语句工作,但无法弄清楚java for条件

java - Gson反序列化接口(interface)到它的类实现

java - 将区域 (100x100px) 写入大文件而不读取目标 jpeg

java - 上传文件 : Request method 'POST' not supported