instanceof Operator (used for Type Comparison)
- instanceof operator compares an object to a specified type.
- instanceof operator test if an object is an instance of a
- class or
- subclass or.
- Any implemented interface.
- By default all reference variable of all classes/interface are instanceof Java.lang.Object class
- null is instanceof nothing.
Program 6 to demonstrate instanceof operator
class SuperClass {}
class SubClass extends SuperClass{}
/** JavaMadeSoEasy.com */
public class InstanceofTest {
public static void main(String[] args) {
SuperClass sup = new SuperClass();
SuperClass sub = new SubClass();
System.out.println("------------------SubClass instanceOf---");
System.out.println("SuperClass instanceof SuperClass - "
+ (sup instanceof SuperClass));
System.out.println("SuperClass instanceof SubClass - "
+ (sup instanceof SubClass));
System.out.println("SuperClass instanceof java.lang.Object - "
+ (sup instanceof java.lang.Object));
System.out.println("\n------------------SubClass instanceOf---");
System.out.println("SubClass instanceof SuperClass - "
+ (sub instanceof SuperClass));
System.out.println("SubClass instanceof SubClass - "
+ (sub instanceof SubClass));
System.out.println("SubClass instanceof java.lang.Object - "
+ (sub instanceof java.lang.Object));
}
}
/*OUTPUT
------------------SubClass instanceOf---
SuperClass instanceof SuperClass - true
SuperClass instanceof SubClass - false
SuperClass instanceof java.lang.Object - true
------------------SuperClass instanceOf---
SubClass instanceof SuperClass - true
SubClass instanceof SubClass - true
SubClass instanceof java.lang.Object - true
*/
|
Labels:
Core Java
core java Basics