OOPS in JAVA 18
instanceof Operator
The 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. instanceof operator return boolean value, either true or false.
Example
public class Test
{
public static void main(String[] args)
{
Test t= new Test();
System.out.println(t instanceof Test);
}
}
Output : true
Example:
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Output: true
Downcasting with java 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.
Dog d=new Animal();//Compilation error
If you perform it by typecasting, ClassCastException is thrown at runtime.
Dog d=(Dog)new Animal();
//Compiles successfully but ClassCastException is thrown at runtime.
But if we use instanceof operator, downcasting is possible
Example : Downcasting with instanceof
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
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )