Java point identifier analysis

What are the rules used by Java to resolve point identifiers?

For instance:

import Foo.Bar; class Foo { public static class Bar { }; }; 

Now Foo.Bar can refer to either the imported Bar class or the one specified in the source code. How is this disagreement resolved?

I tried this one case, so I know what happens in practice, but I'm looking for more than that; I want to know the basic rules. For example, if Foo.Bar exists in the source file, can I still reference the imported class Foo.Bar.Baz ? What if Foo.Bar is a package as well as a class? If the compiler cannot find Foo.Bar in the nearest Foo , will it simply refuse or continue to search for another Foo until it finishes or finds one that matches?

(By the way, I found the corresponding bit in the language specification. It doesn't help much ...)

+6
source share
1 answer

To resolve a strange collision like this, the java compiler follows the same rules that it uses to solve problems such as local variable names that collide with instance field names - it uses the "closest" declaration. In this case, the local class Foo will win over the imported one.

Collision can also occur when two classes with the same name are imported. The most common examples are java.util.Date and java.sql.Date . If you imported them into your class, you should access them using your full name.

+4
source

Source: https://habr.com/ru/post/890410/


All Articles