Static classes in Java - something is hiding

The following is the simplest example of a static inner class in Java. Let's take a look at that.

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); } } 

In the Outer class, there is a static class with the name Internal and a static object with the same name Internal of type Extra. The program displays Whitte on the console, a line in the Extra class through Outer.Inner.s in main (), which is designed to display the line contained in the Internal class in the External class


Why are there no name clashes between a static inner class and a static Extra object? How does the Extra class take precedence over the Internal class and display the string contained in the Advanced class?

+7
source share
2 answers

This is what JLS says. which I consider relevant to your case:

6.3.2 Shaded announcements

A simple name can occur in contexts where it can potentially be interpreted as the name of a variable, type, or package. In these situations, the rules of Β§ 6.5 indicate that a variable will be selected in the type preference, and that the type will be selected in the package preference.

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

A more detailed paragraph 6.3.1 indicates how shadow copy should normally be performed.

+8
source

Because the name of the inner class of the inner class is Outer $ Inner. It is a convenience that you can refer to it as an Inner. I assume that the compiler is aware of this and accepts a more explicit rule for the local variable.

+1
source

All Articles