[英]Creating a method that can return two different things
im trying to make a method that can return two different things based on the type of data that is fed into it. 我试图创建一个方法,可以根据输入到它的数据类型返回两个不同的东西。
this class changes the random item to type of data it is 此类将随机项更改为数据类型
this is what I have, I am aware that in this method that all it is allowed to return is a resource but I'm not sure how to make it that it can return wither a resource or junk. 这就是我所拥有的,我知道在这个方法中,所有允许返回的都是一个资源,但我不知道如何使它能够返回枯竭的资源或垃圾。
public Resource itemToResourceOrJunk(randomItem d){
Resource i;
Junk O;
i = d.getResource();
O = d.getJunk();
if(d.resourceName.equals("notassigned")){
return o;
}
else if(d.junkName.equals("notassigned")){
return i;
}
}
You could have both Resource
and Junk
implement same interface (say Stuff
), and then make the return type itemToResourceOrJunk
to be that interface. 您可以让Resource
和Junk
实现相同的接口(比如Stuff
),然后将返回类型itemToResourceOrJunk
作为该接口。
To be clear, it could go this way: 要清楚,它可以这样:
public class Resource implements Stuff { ... }
and 和
public class Junk implements Stuff { ... }
then 然后
public Stuff itemToResourceOrJunk(randomItem d){ ... }
Though if you need to use methods or properties that are specific to either Resource
or Junk
, then you'd have to cast to the relevant type. 虽然如果您需要使用特定于 Resource
或 Junk
方法或属性 , 那么您必须转换为相关类型。
Let Resource and Junk implement an interface and use that as the return value. 让Resource和Junk实现一个接口并将其用作返回值。
So 所以
public class Resource implements ResourceOrJunk {
...
}
and 和
public class Junk implements ResourceOrJunk {
...
}
interface: 接口:
public interface ResourceOrJunk {
//can be left empty, or add some shared methods
}
now you can change the method to: 现在您可以将方法更改为:
public ResourceOrJunk itemToResourceOrJunk(randomItem d){
and calling methods can check the result: 和调用方法可以检查结果:
ResourceOrJunk roj = itemToResourceOrJunk(d);
if (roj instanceof Resource){
Resource r = (Resource)d;
//do stuff with resource
} else {
Junk j = (Jurk)d;
//do stuff with junk
}
You could change your method to return Object: 您可以更改方法以返回Object:
public Object itemToResourceOrJunk(randomItem d){
...
}
Then the caller would have to use instanceof
to figure out what type of object was actually returned. 然后调用者必须使用instanceof
来确定实际返回的对象类型。
使Resource和Junk实现相同的接口(或扩展相同的类),然后将其用作返回类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.