Java determine which class an object is

前端 未结 6 1742
悲&欢浪女
悲&欢浪女 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条回答
  •  -上瘾入骨i
    2021-01-26 20:55

    You can say if( animal instanceof Carnivore ) to find out if it is a Carnivore or a descendant thereof, and you can use if( animal.getClass() == Carnivore.class ) to find out if it is exactly a Carnivore and not a descendant thereof.

    However, the fact that you need to perform a check of this kind usually means that you have a flaw in your design, a missing overridable method, or something like that.

提交回复
热议问题