Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java How would you use instanceof to return a new object types?

if you have the following

  1. Interface: Meal
  2. Hotdog implements Meal
  3. Burger implements Meal
  4. Salad implements Meal

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!");
  }
like image 669
stackoverflow Avatar asked May 05 '26 22:05

stackoverflow


1 Answers

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); }
}
like image 87
Marko Topolnik Avatar answered May 08 '26 11:05

Marko Topolnik