How to use java instanceof with detail example

The java instanceof operator is used to test whether an object is an instance of a particular type: a class or a subclass, or an interface. The java instanceof operator is also known as the type comparison operator because it compares the instance to the type. It returns true or false. If we apply the java instanceof operator to any variable that has a null value, then it returns false.

How to use java instanceof with detail example

The following example checks to see if the object is the current class.
java-instanceof-example
An object of type subclass is also a type of superclass. For example, if Dog inherits Animal, the Dog object can be referenced by either the Dog class or the Animal class.

Another example of how to use java instanceof with detail example

java-instanceof-example
Example of java instanceof with null variables
If we apply the java instanceof operator to any variable that has a null value, then it returns false. In the following example, we apply the java instanceof operator to null variables.
java-instanceof-example

Downcasting with the java instanceof operator

When subclassing refers to the object of the superclass, it is downcasting. If we do it directly, the compiler will give a compilation error. If you do this by typecasting, then ClassCastException is thrown at runtime. But if we use the java instanceof operator, then downcasting is possible.
java-instanceof-example
If you do downcasting by typecasting, ClassCastException is thrown at runtime.
java-instanceof-example

And possible downcasting with java instanceof

In example after, you will execute downcasting with an java instance of the operator.

java-instanceof-example
Downcasting can also be done without using the java instanceof operator, as follows:

java-instanceof-example
Take a close look at the example above, which is actually referenced by a, which is an object of the Dog class. So if we do downcasting, that's fine. But what if we write:
java-instanceof-example

The actual use of java instanceof 

Take a look at the following example to understand the actual use of the java instanceof keyword in Java:

java-instanceof-example
The output:
java-instanceof-example
To find out more about how to build constructor in java with detail example:

Comments