if you have the following
How would you create a method to take in one of these object types to return the appropriate object?
Example:
Method makeFood(HotDog)
if(HotDog instanceof Meal)
return new HotdogObject();
How do you correctly do this?
I'm working with
static public Food createMeal(Meal f)
throws Exception
{
if (f instanceof Hotdog)
{
return f = new HotDog();
}
if (f instanceof Burger)
{
return f = new Burger();
}
throw new Exception("NotAFood!");
}
Mostly you are confusing classes with their instances. The instanceof operator, as its name says, verifies that an object is an instance of a class, not that a class is a subclass of another. Your particular problem would be solved most elegantly by resorting to reflection:
public static <T extends Meal> T createMeal(Class<T> c) {
try { return c.newInstance(); }
catch (Exception e) { throw new RuntimeException(e); }
}
For example, if you want a Burger, you call
Burger b = createMeal(Burger.class);
But, if you really wanted just another instance of the same type as an instance that you already have, then the code would be
public static Meal createMeal(Meal x) {
try { return x.getClass().newInstance(); }
catch (Exception e) { throw new RuntimeException(e); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With