[Solved] How to do object.getClass().getName() in Java


Looks like you are practicing some OO with Java . It’s better if you ask a doubt instead the full scenario.

However I will paste a sample here and you can ask any doubt you have.
FoodFactory class below, note that for a name you will get the right Object.

public class FoodFactory {

  public Food getFood(String food) {

    if ("Meat".equals(food)) {
      return new Meat();
    } else if ("Fruit".equals(food)) {
      return new Fruit();
    }
    throw new IllegalArgumentException("No food found with name " + food);
  }
}

Both your Food classes should be created, in this case Meat and Fruit.

public class Meat extends Food {
}

Your Food will print message based on current classes. Others will inherit the behavior.

public class Food {
  public void serveFood() {
    System.out.println("I'm serving " + getClass().getSimpleName());
  }
}

Then you can simply run your scenario and note that getClass will run for right hierarchy.

FoodFactory ff = new FoodFactory();
Food f1 = ff.getFood("Fruit");
Food f2 = ff.getFood("Meat");
f1.serveFood();
f2.serveFood();
System.out.println(f1.getClass().getSuperclass().getSimpleName());
System.out.println(f1.getClass().getSimpleName());
System.out.println(f2.getClass().getSimpleName());

Try to play with it and understand.

3

solved How to do object.getClass().getName() in Java