91-9990449935 0120-4256464 |
Java instanceofThe java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false. Simple example of java instanceofLet's see the simple example of instance operator where it tests the current class. Test it NowOutput:true An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be referred by either Dog or Animal class. Another example of java instanceof operatorTest it NowOutput:true instanceof in java with a variable that have null valueIf we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value. Test it NowOutput:false Downcasting with java instanceof operatorWhen Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible. If we perform downcasting by typecasting, ClassCastException is thrown at runtime. Possibility of downcasting with instanceofLet's see the example, where downcasting is possible by instanceof operator. Test it NowOutput:ok downcasting performed Downcasting without the use of java instanceofDowncasting can also be performed without the use of instanceof operator as displayed in the following example: Test it NowOutput:ok downcasting performed Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is fine. But what will happen if we write: Understanding Real use of instanceof in javaLet's see the real use of instanceof keyword by the example given below. Test it NowOutput: b method
Next TopicAbstract class in java
|