Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parsing of dotted identifiers

What are the rules Java uses to resolve dotted identifiers?

For example:

import Foo.Bar;

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

Now, Foo.Bar can refer to either the imported class Bar or the one defined in the source code. How is this kind of ambiguity resolved?

I have tried this one case so I know what happens in practice, but I'm looking for more than that; I want to know the underlying rules. For example, if Foo.Bar exists in the source file, can I still refer to the imported class Foo.Bar.Baz? What if Foo.Bar is a package and also a class? If the compiler can't find Foo.Bar in the closest Foo, does it just give up, or does it keep looking for other Foos until it either runs out or finds one that matches?

(Incidentally, I have found the relevant bit in the language specification. It doesn't help much...)

like image 811
David Given Avatar asked Jun 13 '11 14:06

David Given


1 Answers

To resolve a weird clash like this, the java compiler follows the same rules it uses to resolve things like local variable names clashing with instance field names - it uses the "nearest" declaration. In this case, the local class Foo will win over the imported one.

A clash can also happen when two classes of the same name is being imported. The most common example is java.util.Date and java.sql.Date. If you have imported them both into your class, you must refer to them using their fully qualified name.

like image 102
Bohemian Avatar answered Nov 07 '22 09:11

Bohemian