Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a method that can return two different things

Tags:

java

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;
    }
}
like image 411
Dan2567 Avatar asked Mar 02 '26 03:03

Dan2567


1 Answers

You could have both Resource and Junk implement same interface (say Stuff), and then make the return type itemToResourceOrJunk to be that interface.

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.

like image 189
Igwe Kalu Avatar answered Mar 03 '26 17:03

Igwe Kalu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!