0

Is the mechanism how fields are shadowed/hidden by inheritance and later resolved part of the JVM spec? I know it is part of the Java spec, and can be found in many blog posts and SO questions. However, when I actually look at the JVM spec for field resolution, the words "hiding" or "shadowing" do not appear anywhere in the pdf of the JVM spec.

I ask this because I am writing my own JVM, and discovered that this field shadowing is a property of the bytecode/VM and not just part of the Java compiler or Java-the-language. I want to know the proper, authoritative way this should be implemented at the VM level. Surely a (mis?)feature of the JVM this important needs to be formally documented somewhere?

Kara
  • 6,115
  • 16
  • 50
  • 57
Li Haoyi
  • 15,330
  • 17
  • 80
  • 137

1 Answers1

0

The term shadowing usually refers to when one identifer shadows another. I.e a given name could refer to multiple variables, so there has to be a mechanism to disambiguate it. This is mostly a language level construct because it contains a lot more names. Local variable names don't appear in the bytecode at all except as optional debugging information for instance.

From the bytecode point of view, you already have an explicit reference to a class, name, and descriptor. The only question is whether the field you're describing is actually declared in the class you specified, or whether it was inherited from one of it's superclasses.

As you already discovered, Field Resolution is explained in section 5.4.3.2 of the standard. The terms hiding and shadowing are not used because they apply to source code, not classfiles.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • I'm refering to shadowing of inherited fields though. Field names do appear in bytecode. And I discovered this fact because my DIY JVM (which didn't handle this shadowing) was getting different results for the same bytecode v.s. executing it on a real JVM. Furthermore, when I hacked together some sort of kinda-working inherited-field-shadowing logic into my DIY JVM, they started spitting out the same results in my unit tests. I'm quite sure inherited-field-shadowing is something that the VM has to take care of. – Li Haoyi Mar 23 '13 at 03:09
  • @Li Well the specification for field resolution looks pretty straight forward to me. Where are you having issues? – Antimony Mar 23 '13 at 03:11
  • Do you have any examples of code that the specification fails to cover? I think you may be confused by the fact that while fields are inherited, they are not dispatched virtually like methods are. – Antimony Mar 23 '13 at 03:20
  • Yes, I think you are right. I had assumed that method overriding would be the "default" behavior, and shadowing would get special mention, but it turns out that it's overriding that gets special mention and the shadowing behavior is the default http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.4.5 – Li Haoyi Mar 23 '13 at 15:01