This is a very weird piece of code. The way it is working is that when you type cast null to X.Y, compiler knows that you are referring to the inner class X.Y not the variable Y inside the class X. Then when you access the Z variable, compiler thinks you are trying to access the Z field of the inner class X.Y on an instance of that class. Since the field is static, the compiler will then replace the instance (which is null in this case) on which you are accessing Z with the class name itself, as static fields are accessed on the class not an instance of the class.
If I remember correctly, this is a case of obscuring. There are more details in Java Puzzlers by Bloch and Gafter, but I might not be able to find my copy until Wednesday. That is why you should stick to naming conventions, that fields don't start with CapitalLetters. But the field Y takes precedence over the nested type Y unless you force the type to be used with the cast.
As you say, it is a weird piece of code, but I have seen questions about something like that before.
Get yourself a copy of Java Puzzlers, Excellent book. Or borrow Liutauras' copy. You can't have mine, which I have now found.
Let's see what it says. Obscuring appears on pages 163‑167 and page 182. I read page 163 and knew why I have seen that sort of code before: OP: please always tell us where code comes from. Maybe somebody showed you that code and didn't tell you where it came from. You will find the version with casting nulls on page 166.
Bloch and Gafter pages 163‑164 wrote:. . . . Does the program print Black? Does it print White? Is it even legal?. . . The compiler generally rejects ambiguous programs . . . . it should be illegal . . . it is legal and prints White. . . . When a variable and a type have the same name . . . the variable name takes precedence. . . . obscure the type name.
. . . To remove all ambiguity . . . simply rewrite it to obey the naming conventions. . . .
There is a lot more; you will have to read the original to get that section in its full glory.
The book quotes two Java® Language Specification (=JLS) sections:- JLS‑§6.5.2 and JLS‑§6.3.2 (nowadays §6.4.2). They also say that class names like UUID or URL or URI would be better spelt in mixed case than upper case.