[英]Returning child object from parent class type method
I am trying to write a method that creates random plants and returns the object of created plant as Plant
. 我正在尝试编写一种创建随机植物并将创建的植物的对象返回为
Plant
。 In example below the method createPlant()
is of type Plant
and returns an object of child class Tree
. 在下面的示例中,方法
createPlant()
的类型为Plant
并返回子类Tree
的对象。 As it turns out my way of thinking is erroneous. 事实证明,我的思维方式是错误的。 The error provided by Eclipse is: "This method must return a result of type Plant".
Eclipse提供的错误是:“此方法必须返回Plant类型的结果”。 So how should I go about creating such method?
那么我应该如何创建这种方法呢?
public abstract class Plant {
...
}
public class Tree extends Plant {
...
}
public class Bush extends Plant {
...
}
public class Map {
private Plant plant;
...
public static Plant createPlant(float x, float y) { // This method must return a result of type Plant
Random generator = new Random();
switch (generator.nextInt(2)) {
case 0:
return new Tree(x, y);
case 1:
return new Bush(x, y);
}
}
}
No, from an object oriented perspective this is absolutely okay. 不,从面向对象的角度来看,这绝对可以。 A plant is a general entity, whereas the tree is specialized in some way.
植物是一般实体,而树则以某种方式专门化。
The main point is that the tree is also a plant (is-a-relation) so a method returning a plant can return anything that is at least as general as a plant but also may be more specialized. 重点是,树也是植物(关系),因此返回植物的方法可以返回至少与植物一样普遍但也可能更专业的任何东西。
Add default case of null
. 添加
null
默认大小写。
switch (generator.nextInt(2)) {
case 0:
return new Tree(x, y);
case 1:
return new Bush(x, y);
default: // Requires default case
return null;
}
Or create a dummy NoPlant
class 或创建一个虚拟的
NoPlant
类
public class NoPlant extends Plant {
...
}
Now use in this way 现在以这种方式使用
switch (generator.nextInt(2)) {
case 0:
return new Tree(x, y);
case 1:
return new Bush(x, y);
default: // Requires default case
return new NoPlant();
}
--EDIT-- - 编辑 -
Try in this way also 也可以这样尝试
int random=generator.nextInt(2); // return either 0 or 1
if(random==0){
return new Tree(x,y);
}else{
return new Bush(x, y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.