- Java — Difference between getClass() and instanceof in equals() method?
- Difference between instanceof vs getClass() in Java
- How to Get Type of Object in Java?
- How to Get Type of Object in Java?
- Method 1: Get Type of Pre-defined Class Object Using getClass() Method
- Method 2: Get Type of Pre-defined Class Object Using “instanceof” Operator
- Method 3: Get Type of User-defined Class Object Using getClass() Method
- Method 4: Get Type of User-defined Class Object Using “instanceof” Operator
- Conclusion
- About the author
- Farah Batool
Java — Difference between getClass() and instanceof in equals() method?
You might have seen both getClass() , and instanceof operator in Java can be used in the equals() method to verify the type of the object you are checking for equality. Do you know what the difference is between using getClass() vs instanceof operator in Java? What would be the consequence of using one over the other in the equals() method? This is one of the tricky Java interview questions, which some of you might have encountered. There is a very subtle difference between getClass() and instanceof operator, which can cause potential issues with respect to the equals() method.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
This can break the symmetry clause of the equals() method but can also be leveraged for flexibility and performance as Hibernate does by using proxies in place of actual classes. Let’s see some code examples to understand this difference better.
Difference between instanceof vs getClass() in Java
Before jumping into the equals() method and how they break the symmetry clause let’s verify the behavior getClass() and instanceof operator in Java. Consider the below code, what do you think it will return, true or false?
boolean result = (loader.getClass() == Thread.class); // true result = (loader.getClass() == Runnable.class); // false because we are testing against Runnable result = loader instanceof Thread; // true because the loader is an object of Thread class result = loader instanceof Runnable; // true because the loader is an instance of Thread // and it implements Runnable
So, you can see that getClass() put a restriction that objects are only equal to other objects of the same class, the same runtime type, but instanceof operator returns true for subclass as well.
If you use the getClass() in the equals() method then it will only return true if the other object is also of the same class or same runtime type, it will return false even if its object of subclass and follow the Liskov substitution principle.
Due to this restriction, many Java developers including the great Joshua Bloch have recommended using the instanceof operator in equals() method.
The instanceof operator lets you implement equality between super class and sub class. This is very important from the Collections framework perspective which uses the equals() method to find values. If you use the instanceof operator in equals() method then you can retrieve values even with the object of the subclass as a key provided they have the same content, but this is not possible when you use the getClass() method.
Hibernate relies for its performance gain on this behavior of instanceof operator. If you remember, there is a restriction in place for any Entity or Persistence class in Hibernate that it cannot be final.
This is because hibernate internally creates Proxy classes by extending your Entity class and use it until you really need an attribute from the database. Since instanceof is used to verify the type of object, a Proxy can be equal to the original object.
On the other hand, using instanceof operator has one disadvantage as well. It doesn’t respect the symmetry contract of equals() method. The symmetry property says that if x.equals(y) is true then y.equals(x) should also be true, but if you swap x with subclass then x instanceof y would be true but y instanceof x will be false, hence equals() method will return false.
This is the fact you should consider when deciding whether to use getClass() or instanceof operator for overriding equals() in Java.
That’s all on the difference between getClass() and instanceof in Java. Just remember that getClass() return false if you compare it with the instanceof the subclass but the instance of operator trues if the object is a subclass of the class on the right-hand side of the operator.
The biggest disadvantage of using getClass() in the equals() method is the fact that you get two objects that appear to be equal (because they are equal on all the fields) but they are not equal because they are of different classes.
This can cause surprising behavior hence Joshua Bloch and others recommend using the instanceof operator inside equals() method in Java.
How to Get Type of Object in Java?
An object is a physical entity that has its own state and behavior, and it acts as a unique instance of a Java class. It. When the object originates from a source, it is considered useful to examine the object type. Also, knowing the type of an object is crucial when working with a collection that includes different objects or when it is required to execute the logical operation with the same kind of variables.
This article will help you to learn the method to get the type of an object in Java.
How to Get Type of Object in Java?
For getting the type of predefined or user-defined class object in Java, you can use:
We will now check out each of the mentioned methods one by one!
Method 1: Get Type of Pre-defined Class Object Using getClass() Method
In Java, we have predefined classes like wrapper classes such as String, Double, Integer, and many more. Sometimes we need to verify the object type while using predefined classes. For this purpose, Java offers a “getClass()” method that belongs to the “Object” class.
Syntax
The syntax of the “getClass()” method is given as follows:
Here, the “getClass()” method will return the class of the specified “x” object.
Example
In this example, we will create a String type object named “x” containing the following value:
Next, we will print a statement using the “System.out.println()” method:
Lastly, we will get the type of the object “x” by calling the “getClass()” method:
The output shows that the created variable belongs to the Java String class:
Let’s see another method to get the object type using the “instanceof” operator.
Method 2: Get Type of Pre-defined Class Object Using “instanceof” Operator
You can also utilize the “instanceof” operator to check the object type in a Java program. This operator returns a boolean value which indicates whether the object is an instance of the particular class or not.
Syntax
The syntax of the “instanceof” is as follows:
Here, “x” is an object and “Integer” is the predefined Java wrapper class. The “instanceof” operator checks whether the object belongs to the mentioned class or not and returns a boolean value.
Example
In this example, we have an object “x” of the Integer class having “5” as its value:
Next, we will print a statement using the “System.out.println()” method:
Now, we will check whether the object is an instance of an Integer class or not:
The output displayed “true” as the object “x” is an instance of the Integer class:
At this point, you may be wondering about how to get the type of user-defined class object. The below-given section will assist you in this regard.
Method 3: Get Type of User-defined Class Object Using getClass() Method
You can also get the type of the user-defined class object with the help of the “getClass()” method. In such a scenario, we will compare the object with the class name using the “==” comparison operator.
Syntax
For the specified purpose, the syntax of “getClass()” method is given as:
Here, the “getClass()” method is called by the “myclassObj” object of the “MyClass” and then compared with the name using the comparison operator “==”.
Example
In this example, we have three classes named “MyClass”, “MynewClass”, and “Example”, where MyClass acts as a parent class of MynewClass:
The “MynewClass” is a child class as it is extended from “MyClass”:
In the main() method of the class “Example”, we will declare and instantiate an object of the parent class “MyClass”. Then check whether the created object belongs to which class; parent or child? To do so, we will call the “getClass()” method with the created object and compare the resultant value with parent and child class names using if-else-if conditions:
public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj. getClass ( ) == MyClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MyClass'» ) ;
} else if ( myclassObj. getClass ( ) == MynewClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MynewClass'» ) ;
}
}
}
The output indicates that the object “myclassObj” belongs to the parent class named “MyClass”:
Now, head toward the next section!
Method 4: Get Type of User-defined Class Object Using “instanceof” Operator
Similar to predefined classes, for user-defined classes, you can also get the type of object by using the “instanceof” operator.
Syntax
The syntax is given below:
Here, the “instanceof” operator will check if the “myclassObj” is an instance of “MyClass” or not.
Example
We will now utilize the same classes which we have created in the previously mentioned example. The only difference is that we will use the “instanceof” operator to verify if the created object instance belongs to the parent or child class:
public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj instanceof MyClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MyClass'» ) ;
} else if ( myclassObj instanceof MynewClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MynewClass'» ) ;
}
}
}
The given output shows that the “instanceof” operator validated the type of the object as “MyClass”:
We have compiled all methods related to getting object type in Java.
Conclusion
To get a type of object in Java, you can use the “getClass()” method or the “instanceof” operator. These methods can be used to check object types for both predefined and user-defined classes. The getClass() method returns the class name while the “instanceof” operator returns a boolean value, where “true” indicates the object belongs to that specified class; otherwise, it returns “false”. This article provided all the methods to get the object type in Java.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.