instanceOf operator in Java

 In Java instanceOf operator is used to check if the reference variable is of the particular type(class,interface) or not. instanceOf  operator returns boolean value i.e. true or false.

So we are going to make it clear with a small example to understand how instanceOf works in java.

                                                        Program:1

package com.javainstance;

class Vehicle {

};

class Car extends Vehicle {

public static void main(String[] args) {

Vehicle a = new Vehicle();

Car b = new Car();

System.out.println(a instanceof Vehicle);
System.out.println(b instanceof Car);
System.out.println(b instanceof Vehicle);
System.out.println(a instanceof Car);

}

};
                                                                      
Output:

true
true
true
false
                                                               

From the above example, it is very clear that  subclass is an instance of the super class but super class is not the instance of the subclass.

Now we are going to make a small change in the above code and add two lines highlighted below.

                                                                    Program:2
package com.javainstance;

class Vehicle {

};

class Car extends Vehicle {

public static void main(String[] args) {

Vehicle a = new Vehicle();

Car b = new Car();

System.out.println(a instanceof Vehicle);
System.out.println(b instanceof Car);
System.out.println(b instanceof Vehicle);
System.out.println(a instanceof Car);
//a=b;
b=(Car) a;

}

};

                                                                  

Upcasting

  • When we right a=b i.e we are doing upcasting and run the program.It works fine

Downcasting 

When we remove a=b and add b=a it gives a compilation error. Now typecast is to subclass compilation error in gone but it throws below exception at runtime.

Exception in thread "main" java.lang.ClassCastException: com.javainstance.Vehicle cannot be cast to com.javainstance.Car at com.javainstance.Car.main(Car.java:21)

Now if you relate Program 1 and Program 2 you can figure out that we are getting exception only when output is false i.e a is not instanceOf b but we are typecasting it (a is not the instanceOf Car).

Thus to avoid this runtime exception we can check at compile time itself that if the object is instanceOf another object then only typecast.

Hope you instanceOf concept is clear.

You may be interested in Recommended Books For Java Interview.

Give you suggestion in comments.If you like the post Share with your friends on social network.




















instanceOf operator in Java instanceOf operator in Java Reviewed by JavaInstance on 10:43:00 AM Rating: 5

No comments:

Powered by Blogger.