In this blog, we are going to learn about `instanceof` in Java and its use case with the help of examples.
In object-oriented programming, writing a program efficiently is good practice. Additionally, knowing how to check an object’s type is crucial for creating strong and bug-free applications.
Java offers the `instanceof` operator to help programmers determine an object’s type at runtime.
Instanceof operator in Java
Definition:
An object in Java uses the binary operator ‘instanceof’ to determine if it is an instance of a specific class or implements a particular interface.
This check is typically performed at runtime.
Syntax:
object instanceof ClassName
Sample Example 1 :
class InsOf{ // class Insof public static void main(String args[]){ InsOf io = new InsOf(); // create instance of class InsOf System.out.println(io instanceof InsOf); //true } }
Output :
true
In given example,
‘InsOf’ is the main class.
An instance of InsOf is created and checked against InsOf using the instanceof operator, which will return true as it is an instance of class ‘InsOf’.
Sample Example 2 :
class InsOf1 {} class InsOf2 {} public class Main { public static void main(String args[]) { InsOf2 io = new InsOf2(); // create instance of class InsOf2 System.out.println(io instanceof InsOf1); // false } }
Output :
false
In given example,
InsOf1 is the original class. However, InsOf2 is a new class that does not extend InsOf1. It returns false because an instance of InsOf2 is created. When checked against InsOf1 using instanceof instead of InsOf2, io is not an instance of InsOf1.
It’s important to note that instanceof checks the prototype chain; therefore, it also returns true if the object inherits from the specified class or constructor function.
Conclusion
In conclusion, an instanceof in Java is a binary operator which works as a detective tool that helps programmers check what type an object is when their program is running.
By using the instanceof operator, we can make your programs more reliable and easier to understand.
Though using these instanceof operator, there is also the getclass() which returns the runtime class of the particular object.