So, (b instanceof A a) will not compile because the compiler knows that b will always point to an instanceof A and this check is pointless. This is a new feature of instanceof that is applicable only when used with pattern matching.
Can you tell me which part of this explanation is not clear?
If you like our products and services, please help us by posting your review here.
No, the code that you have written above doesn't compile. You can try it out on your machine also. The error message is "error: expression type B is a subtype of pattern type A if(b instanceof A a) {" and the reason is the same that is given.
So I still don't understand what is your confusion.
If you like our products and services, please help us by posting your review here.
public class C {
public static void main(String args[]) {
B b = new B();
if((b instanceof A a)) {
System.out.println("Works");
}
}
}
I run C and get "Works". I did the same as inner classes in one file and result is the same.
By the way, I am using Java Version 17, not sure about later version.
I think Java changed the behavior because I compiled it with JDK 17.0.3 and it failed to compile. I then compiled it with Java 21 and it compiled without any error. Something changed between the versions.
So I will need to dig into it further to find out what is going on.
If you like our products and services, please help us by posting your review here.