The instanceof operator is used to identify object is instance of particular class or not. It is used to get information of object at run time. If object is type of particular class, an instance of subclass, instance of class that implement particular interface then it return true otherwise false.
Below is simple example to understand basic functionality of instanceof operator.
package com.kodemaker; import java.util.ArrayList; import java.util.List; public class InstancofExample { public static void main(String[] args) { List<Object> genericList = new ArrayList<>(); genericList.add(new Integer(2)); genericList.add(new Double(2)); genericList.add(new Boolean(true)); genericList.add(new InstancofExample()); for(Object obj :genericList){ if(obj instanceof Integer){ System.out.println("Integer "+obj); }else if(obj instanceof Double){ System.out.println("Double "+obj); }else if(obj instanceof Boolean){ System.out.println("Boolean "+obj); }else if(obj instanceof InstancofExample){ System.out.println("InstancofExample "+obj); } } } }
Output of above programme
Integer 2 Double 2.0 Boolean true InstancofExample com.kodemaker.InstancofExample@2a139a55
Null is not instance of anything,.In this case instanceof always return false.
package com.kodemaker; public class NullInstanceExample { public static void main(String[] args) { System.out.println(null instanceof Integer); } }
Output of above programme
false
Now we consider How we can use instanceof operator at hierarchy level.
In Below example
1. Base class,
2. Interface
3. Child class which extends Base class and implement Instance Interface
Base Class
package com.kodemaker; public class BaseClass {
}
Interface
package com.kodemaker; public interface InstanceInterface { }
Child Class
package com.kodemaker; public class ChildClass extends BaseClass implements InstanceInterface{ }
Main Class
package com.kodemaker; public class InstanceMain { public static void main(String[] args) { BaseClass baseClass = new BaseClass(); System.out.println(baseClass instanceof BaseClass); ChildClass childClass = new ChildClass(); System.out.println(childClass instanceof ChildClass); System.out.println(childClass instanceof BaseClass); System.out.println(childClass instanceof InstanceInterface); } }
System.out.println(baseClass instanceof BaseClass);
Print true because Baseclass instance of BaseClass.
System.out.println(childClass instanceof ChildClass);
Print true because childClass extend BaseClass.
System.out.println(childClass instanceof InstanceInterface);
Print true because childClass implements InstanceInterface.
mostly instanceof used when we are not aware about type of object and we want to runtime assign object to particular variable of class. If we assign object to wrong class variable then exception will be thrown.
Reference
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
No comments:
Post a Comment