This is probably a bad thing to do, as discussed in Can parent and child class in Java have same instance variable?. (What if the parent variable name is changed? Then it will not be shadowed anymore.) However, I am still curious whether variables that are differently static/nonstatic will shadow each other. On one hand I would expect they are the same variable name so would be shadowed, but on the other hand it seems like the compiler might distinguish between the two based on staticness.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
From The Java Language Specification:
If a method in a superclass refers to a particular field (static or otherwise) of that class, only that class's declaration of the field will be in scope at that point; any fields (static or otherwise) of subclasses will not be in scope. Therefore, the method will always use the superclass field, even if a subclass inherits it and shadows that field.
This answer is completely rewritten based on my new understanding of the question. Below is my first answer, kept for posterity.
From The Java Language Specification:
This suggests that compilers are required to shadow parent variables, regardless of staticness.
Note that none of this is relevant to inherited methods, which always use the original variables regardless of whether a subclass shadows them. I suspect this isn't what you meant to ask.
they will:
Look at the code below. If you want access
field
from theChildClass
, it will use its own member variable. If you want to access the staticfield
fromSuperClass
, you have to call it explicitly by usingSuperClass.field
. The `STATIC_FIELD`` can be accessed directly since there is no ambiguity to the compiler.See also 15.11.1 and 15.11.2 in here and 8.3 in here
With Eclipse's compiler, methods from the parent class will still use the member variables from the superclass, not the shadowed variables from the child class, as shown below. This is an only slightly modified version of thinksteep's answer.
As per Java language specification:
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
A hidden field can be accessed by using a qualified name (if it is static)
JVM Specification
You may refer "Field Declarations" section.