Java – create a method that can return two different contents
•
Java
I'm trying to create a method that returns two different things based on the data type entered into it
This class changes random items to data types
This is what I have. I know that in this method, all that is allowed to return is a resource, but I don't know how to make it return exhausted resources or garbage
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;
}
}
Solution
Let resource and junk implement an interface and use it as a return value
therefore
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 call methods to check the results:
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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
