Recently I observed a noticeable behavior of instanceof operator while working with interfaces and classes. Let me explain with an example.
InstanceOfDemo.javapublic class InstanceOfDemo { static interface A{} static class B{} static class C{} public static void main(String args[]) { B obj = new B(); System.out.println(obj instanceof A); System.out.println(obj instanceof B); System.out.println(obj instanceof C); } }
When I try
to compile the above program, I end up in compiler error.
It is because Java does not support multiple class inheritance, so it is known during the compilation that an object of type B cannot be a subtype of C. On the other hand, it is possible that obj can be an instance of interface A.
InstanceOfDemo.javapublic class InstanceOfDemo { static interface A{} static class B{} static class C{} static class D extends B implements A{} public static void main(String args[]) { B obj = new D(); System.out.println(obj instanceof A); } }
You may like
Explain Loop inversion in Java
Check whether I have JDK or JRE in my system
How to check whether string contain only whitespaces or not?
How to call base class method from subclass overriding method?
No comments:
Post a Comment