Thursday, June 4, 2015

instanceof




// instanceof simply means objectof
// referenceVariable instanceOf className/interfaceName
// Test whether the reference variable on the left is an instance/object
// of the specified type(class or subClass or interface) on the right

// An object of subclass type is also a type of parent class
// instanceOf operator with a variable that has null value returns false
// Parent class can never be converted into child but child class can be converted into the parent



public class InstanceOfDemo
{
public static void main(String[] args)
{
Parent p = new Parent();
System.out.println(p instanceof Parent);
System.out.println(p instanceof Child);   // Parent can never be the instance of child
System.out.println();

Child cc = new Child();
System.out.println(cc instanceof Child);
System.out.println(cc instanceof Parent);
System.out.println();

Parent p1 = new Child();
System.out.println(p1 instanceof Child);
System.out.println(p1 instanceof Parent);
System.out.println();

Child c = (Child) p1;
System.out.println(c instanceof Child);
System.out.println(c instanceof Parent);
System.out.println();

Parent pp = p1;
System.out.println(pp instanceof Parent);
System.out.println(pp instanceof Child);
System.out.println();

Child c1 = (Child) p; // class cast exception
System.out.println(c1 instanceof Child);
System.out.println(c1 instanceof Parent);
}
}


class Parent
{

}


class Child extends Parent
{

}



No comments:

Post a Comment