鉴于以下类,我决定基于 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/