Java determine which class an object is

2020-04-21 01:44发布

I have three classes (Carnivore, Herbivore, and Plant) that extend another class (Organism). How can I tell which subclass an object is a part of? So far I have a property that has the classes' name, but I think it could be possible to use an operator similar to javascript's typeof. (Similar to: Organism typeof Carnivore)

6条回答
贪生不怕死
2楼-- · 2020-04-21 02:22

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

查看更多
做自己的国王
3楼-- · 2020-04-21 02:31

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.

查看更多
等我变得足够好
4楼-- · 2020-04-21 02:32

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

查看更多
对你真心纯属浪费
5楼-- · 2020-04-21 02:34

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.

查看更多
时光不老,我们不散
6楼-- · 2020-04-21 02:35

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.

查看更多
唯我独甜
7楼-- · 2020-04-21 02:38

You can use the instanceof operator

查看更多
登录 后发表回答