class A { } class B extends A { } public class Main { public static void main(String[] args) { A a = new A(); //A a = null; //Also check //A.class.isAssignableFrom(cls); B b = new B(); A ab = new B(); if (a instanceof A) { System.out.println("a instanceof A - true"); } else { System.out.println("a instanceof A - false"); } if (a instanceof B) { System.out.println("a instanceof B - true"); } else { System.out.println("a instanceof B - false"); } if (b instanceof A) { System.out.println("b instanceof A - true"); } else { System.out.println("b instanceof A - false"); } if (b instanceof B) { System.out.println("b instanceof B - true"); } else { System.out.println("b instanceof B - false"); } if (ab instanceof A) { System.out.println("ab instanceof A - true"); } else { System.out.println("ab instanceof A - false"); } if (ab instanceof B) { System.out.println("ab instanceof B - true"); } else { System.out.println("ab instanceof B - false"); } } } Result: a instanceof A - true a instanceof B - false b instanceof A - true b instanceof B - true ab instanceof A - true ab instanceof B - true
Sunday, February 19, 2012
Java Nuggets
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment