The instanceof operator is used to determine whether or not a reference variable contains a specific type of object reference.
Because it compares the instance to the type, the instanceof operator in Java is also known as the type comparison operator. It either returns true or false. We get false when using the instanceof operator on a variable with a null value.
(object) instanceof (type)
where,
object: It is an object reference variable.
type: It can be a class or an interface.
// Java Program to Illustrate instanceof Keyword
// Importing required I/O classes
import java.io.*;
// Main class
class Demo {
public static void main(String[] args)
{
// Creating object of class inside main()
Demo object = new Demo();
// Returning instanceof
System.out.println(object instanceof Demo);
}
}
true
class Parent { }
class Child extends Parent { }
class Test
{
public static void main(String[] args)
{
// Reference is Parent type but object is
// of child type.
Parent cobj = new Child();
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");
}
}
cobj is an instance of Child
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
false
Downcasting occurs when a Subclass type refers to a Parent class object. If we do it manually, the compiler will give us a Compilation Error. You’ll get a ClassCastException at runtime if you do it using typecasting. Downcasting is possible, though, if we use the instanceof operator.
Dog d=new Animal();//Compilation error
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
Dog d=(Dog)new Animal();
//Compiles successfully but ClassCastException is thrown at runtime
class Animal { }
class Dog3 extends Animal {
static void method(Animal a) {
if(a instanceof Dog3){
Dog3 d=(Dog3)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
}
}
ok downcasting performed
Note: also read about the Final keyword in Java
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…