Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static classes in Java--something is being shadowed

Tags:

java

Following is the simplest example of static inner class in Java. Let's look at it.

package staticclass;

final class Outer
{
    final public static class Inner
    {
        static String s = "Black";
    }

    static Extra Inner = new Extra();   //The inner class name and the object name of the class  Extra are same and it is responsible for shadowing/hiding Inner.s
}

final class Extra
{
    String s = "White";
}

final public class Main
{
    public static void main(String[] args)
    {
        System.out.println(Outer.Inner.s);
    }
}

Within the Outer class, there is a static class named Inner and a static object with the same name Inner of type Extra. The program displays Whilte on the console, a string in the Extra class through Outer.Inner.s in main() which is intended to display the string contained in the Inner class within the Outer class


Why is there no name collision between a static inner class and a static object of type Extra? How does the Extra class enjoys the higher priority than the Inner class and displays the string contained in the Extra class?

like image 625
Lion Avatar asked Nov 15 '11 00:11

Lion


1 Answers

This is what the JLS says. which I believe applies to your case:

6.3.2 Obscured Declarations

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.

So since your static Extra Inner = new Extra() is a variable, it will be chosen over final public static class Inner which is a type.

The quite more elaborate paragraph 6.3.1 specifies how shadowing generally is to be resolved.

like image 173
nos Avatar answered Sep 24 '22 19:09

nos