instanceof operator-2
instanceof operator with a variable that have null value
If 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.
class Dog{
public static void main(String args[]){
Dog d=null;
System.out.println(d instanceof Dog);//false
}
}
Output:false
Downcasting with instanceof operator
When 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.
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
Possibility of downcasting with instanceof operator
Let's see the example, where downcasting is possible by instanceof operator.
class Animal { }
class Dog extends Animal {
static void method(Animal a) {
if(a instanceof Dog){
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog();
Dog.method(a);
}
}
Output:ok downcasting performed
Downcasting without the use of instanceof operator
Downcasting can also be performed without the use of instanceof operator as displayed in the following example:
class Animal { }
class Dog extends Animal {
static void method(Animal a) {
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Animal a=new Dog();
Dog.method(a);
}
}
Output: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:
Animal a=new Animal();
Dog.method(a);
//Now ClassCastException but not in case of instanceof operator
No comments:
Post a Comment