Search code examples
javaclassscoping

Shadowing Precedence Ordering for an outer variable vs an inherited variable


If I have an inner class that is in the context of an outer class that defines some field "foo", and that inner class inherits from another class that also has a "foo" field, which foo is visible within the inner class?

Here is an example. Which x is being accessed?

class OuterClass {
    int x;
    class NestedClass extends OtherClass {
        int y = x  /* which x is accessed here */
    }
}


class OtherClass {
    int x;
}

Solution

  • As it says here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

    If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope.

    So, the variable of the parent class will be visible. You can try and see for yourself that this is the case.

    As an extra bit of information, If you want to access the variable in the outer class, you can do so using OuterClassName.this.foo.