Java determine which class an object is

前端 未结 6 1795
悲&欢浪女
悲&欢浪女 2021-01-26 20:36

I have three classes (Carnivore, Herbivore, and Plant) that extend another class (Organism). How can I tell which subclass an

6条回答
  •  执念已碎
    2021-01-26 21:07

    You can use the instanceof keyword.

    Note, however, that needing to use this is often a sign of a bad design. You should typically write method overrides in each of your derived classes so that you don't explicitly need to check which class something is.

提交回复
热议问题