问题
Suppose we have a package called com.example1 containing a Hello class (along with other classes).
Then we have another package com.example2 also containing a Hello class (obviously with different behaviour).
Now let's suppose we need every class in com.example1 and the Hello class in com.example2
import com.example1.*;
import com.example2.Hello;
Which one gets called in this case?
Hello hello = new Hello();
Or does this give a compile error?
This is just a theoretical question out of curiosity.
Since packages were created to avoid naming conflict, what happens when two packages contain two classes with the same name?
回答1:
It will give a compile error. You have to explicitly name the class - com.example2.Hello hello = new com.example2.Hello();
回答2:
Instead of leaving it to chance, it would be best to be explicit in your declarations. It is a compile error.
A similar clash often happens with java.util.List and java.awt.List. If you are explicit, there is no confusion.
回答3:
It will not give a compiler error as stated by other users. It will use com.example2.Hello. This is because explicit import (com.example2.Hello) will always have precedence over * import (com.example1.*).
来源:https://stackoverflow.com/questions/3501514/resolving-package-conflict