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.
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.
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.
If you do downcasting by typecasting, ClassCastException is thrown at runtime.
Downcasting can also be done without using the java instanceof operator, as follows:
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:
The output:
To find out more about how to build constructor in java with detail example:
How to use java instanceof with detail example
The following example checks to see if the object is the current class.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
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.
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.If you do downcasting by typecasting, ClassCastException is thrown at runtime.
And possible downcasting with java instanceof
In example after, you will execute downcasting with an java instance of the operator.Downcasting can also be done without using the java instanceof operator, as follows:
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:
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:The output:
To find out more about how to build constructor in java with detail example:
Comments
Post a Comment