Compare Class Types of Two Objects in Java

If you have two objects and want to determine whether they are instances of the same class, this is easy to do in Java.

Cow c = new Cow();

Print(c instanceof Cow); //true
Print(c instanceof Horse); //false

This also works when you have a class hierarchy (inheritance). The instanceof operator will return true if the object can be “upcast” to that class. So now let’s assume you also have an Animal class, and Cow inherits from Animal. You would get:

Print(c instanceof Cow); //true
Print(c instanceof Animal); //true

Let’s say you are handling the object as its parent class (in this case Animal). You would get the following behavior.

Animal a = new Cow();
Print(a instanceof Cow); //true;
Print(a instanceof Animal); //true

2 Responses to “Compare Class Types of Two Objects in Java”

  1. if you want to compare class type of two objects, as you titled, you can either use (a instanceof b) or a.getClass()== b.getClass().

  2. I was told that using .getClass() and == to compare classes is the more proper way to approach this. I was wondering if anyone with experience could confirm or deny this.

Leave a Reply