Friday 27 September 2013

instanceof

The instanceof is one of the keywords that helps you in finding the object type at runtime. For example, in runtime, your method is returning an object on which you have to do something where you are not expecting the runtime error like class cast exception whih terminates your program unexpectedly. At this time this instanceof keyword helps in finding the type of your object.


Eg:

public class InstanceOfDemo {

public static void main(String args[]){

Base base = new Base();
Derived derived = new Derived();
Base baseDerived = new Derived();

System.out.println("Base instanceof Base: " + (base instanceof Base));
System.out.println("Base instanceof Derived: " + (base instanceof Derived));
System.out.println("Derived instanceof Base: " + (derived instanceof Base));
System.out.println("Derived instanceof Derived: " + (derived instanceof Derived));
System.out.println("BaseDerived instanceof Base: " + (baseDerived instanceof Base));
System.out.println("BaseDerived instanceof Derived: " + (baseDerived instanceof Derived));

}


}
class Base{
//some variable declarations and method definitions here
}
class Derived extends Base{
//some variable declarations and method definitions here
}

Result:
Base instanceof Base: true
Base instanceof Derived: false
Derived instanceof Base: true
Derived instanceof Derived: true
BaseDerived instanceof Base: true
BaseDerived instanceof Derived: true

No comments:

Post a Comment