Java determines which class is an object

I have three classes ( Carnivore , Herbivore and Plant ) that extend another class ( Organism ). How can I determine which subclass an object is in? So far I have a property that has a class name, but I think it would be possible to use a statement similar to javascript typeof. (Similar to: Organism typeof Carnivore )

+1
java object oop class
source share
6 answers

You can use the instanceof keyword.

Please note, however, that using this is often a sign of poor design. Typically, you should write method overrides in each of your derived classes so that you clearly do not need to check which class is.

+3
source share

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

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

+2
source share

Java has an instanceof operator. However, this type of thing may contradict object-oriented design.

+1
source share

You can use instanceof operator

0
source share

Look at the instanceof statement

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

Please note that although many people think that using this can be considered dangerous, they are even compared to GOTO , but this is not bad in some cases . You can use it, but not very often.

0
source share

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

0
source share

All Articles