instanceof vs isInstance():
instanceof: It is used to find the Object is a particular type or not .
Example:
Thread t=new Thread();
System.out.println(t instanceof Runnable);
In above example we know particular type i.e., Runnable,we are checking whether the given object 't' is Runnable type or not.
isInstance(): when we don't know the particular type at starting to check whether the given object is of particular type or not. For this we have to check the type of the given object dynamically at run time as shown below example
Example:
class Test {
public static void main(String args) throws Exception{
Thread t=new Thread();
System.out.println(Class.forName(args[0]).isInstance(t));
}
}
output:
java Test java.lang.Runnable
o/p:true
java Test String
o/p:false
instanceof: It is used to find the Object is a particular type or not .
Example:
Thread t=new Thread();
System.out.println(t instanceof Runnable);
In above example we know particular type i.e., Runnable,we are checking whether the given object 't' is Runnable type or not.
isInstance(): when we don't know the particular type at starting to check whether the given object is of particular type or not. For this we have to check the type of the given object dynamically at run time as shown below example
Example:
class Test {
public static void main(String args) throws Exception{
Thread t=new Thread();
System.out.println(Class.forName(args[0]).isInstance(t));
}
}
output:
java Test java.lang.Runnable
o/p:true
java Test String
o/p:false
No comments:
Post a Comment
If you Like my blog Spread it and help friends for whom this blog is useful for their career.