By
using 'isInstance()', instanceof operator, you can check whether the object can
be casted to other type or not.
For
example, let’s see the definition of Integer class, it looks like below.
public
final class Integer extends Number implements Comparable<Integer> {
}
As
you see, Integer is a subclass of Number, Comparable, and Object (Object is the
super class for all the classes). Now if you define, an integer variable, you
can assign it to Number, Comparable and Object types. You can check this
compatibility using 'isInstance' method.
package com.sample.test; public class Test { public static void main(String args[]) { Integer var1 = new Integer(10); System.out.println("Can I assign var1 to Integer : " + Integer.class.isInstance(var1)); System.out.println("Can I assign var1 to Number : " + Number.class.isInstance(var1)); System.out.println("Can I assign var1 to Comparable : " + Comparable.class.isInstance(var1)); System.out.println("Can I assign var1 to Object : " + Object.class.isInstance(var1)); System.out.println("Can I assign var1 to Double : " + Double.class.isInstance(var1)); System.out.println("Can I assign var1 to Float : " + Float.class.isInstance(var1)); } }
Output
Can I assign var1 to Integer : true Can I assign var1 to Number : true Can I assign var1 to Comparable : true Can I assign var1 to Object : true Can I assign var1 to Double : false Can I assign var1 to Float : false
No comments:
Post a Comment