Thursday 6 January 2022

instanceof operator behavior with interface and class

 Recently I observed a noticeable behavior of instanceof operator while working with interfaces and classes. Let me explain with an example.

InstanceOfDemo.java
public 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.java
public 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);
	}
}

In the above snippet, by looking at 'obj instanceof A' expression compiler cannot deduce in advance whether will it evaluate to true or false, but by looking at 'obj instanceof C' compiler knows that this is always evaluated to false, which is meaningless and helps you to prevent an error.




You may like

Interview Questions

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?

Can an interface extend multiple interfaces in Java?

No comments:

Post a Comment