Java determine which class an object is

前端 未结 6 1738
悲&欢浪女
悲&欢浪女 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 20:52

    Java has an instanceof operator. However, that type of thing can be contrary to object-oriented design.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-26 20:56

    Take a look at instanceof operator

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

    Note that although many people thinks that using it may be considered dangerous, they even compare to GOTO, but it's not bad in some cases. You can use it, but not really often.

    0 讨论(0)
  • 2021-01-26 21:02

    objInstance instanceof Carnivore. Here objInstance is the object you want to test.

    0 讨论(0)
  • 2021-01-26 21:05

    You can use the instanceof operator

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题