In the following code, the type of x is I (although x also implements J but thats not known at compile time) so why is it that the code at (1) doesn’t result in a compile time error.
Because at compile time only the type of the reference is considered.
public class MyClass {
public static void main(String[] args) {
I x = new D();
if (x instanceof J) //(1)
System.out.println("J");
}
}
interface I {}
interface J {}
class C implements I {}
class D extends C implements J {}
instanceofis used used for runtime determination of an object’s type. You are trying to determine ifxis really an object of typeJwhen the program is running, so it compiles.Were you thinking it should result in a compile-time error because you think the compiler does not know
x‘s type?Edit
As Kirk Woll has commented (thanks Kirk Woll!), if you were checking if
xis aninstanceofa concrete class, and the compiler can determinex‘s type, then you will get an error at compile time.From the Java Language Specification:
As an example of this: