Say you have created a class called X and one of your methods in class X needs to return an instance of class X but this time the class X has the same name but it is another class from a jar file that just happens to have the same name. Is there a way to reference which class X you want?
-
1The first sentence is too long to understand. can you show us exactly what is your problem? – Dimitri Aug 16 '11 at 15:03
-
I believe that this thread answers your question: [http://stackoverflow.com/questions/2079823/importing-two-classes-with-same-name-how-to-handle][1] [1]: http://stackoverflow.com/questions/2079823/importing-two-classes-with-same-name-how-to-handle – Travis Nelson Aug 16 '11 at 15:07
4 Answers
As long as they have different package names, refer to the class from the other jar file by its fully qualied name, as in com.packagename.X
.

- 14,395
- 3
- 38
- 48
Yes, by specifying a fully qualified class name (as you can't have 2 identical class names in the same package).
E.g. let's say you have 2 classes with the same names (in 2 diferent package)
za.org.myDomain.factory.ClassAFactory
za.org.myDomain.subDomain.factory.ClassAFactory
and have imported only 1 of the class:
import za.org.myDomain.factory.ClassAFactory;
you can do something of this (e.g. in the abstract class ClassFactory
):
public abstract ClassAFactory getAFactory();
public abstract za.org.myDomain.subDomain.factory.ClassAFactory getFactory();
The 2nd import doesn't have to have an import
declaration since you fully qualified the return type.

- 87,898
- 29
- 167
- 228
You have to reference it by the full name, eg: com.something.something.ClassName

- 87,898
- 29
- 167
- 228

- 376
- 1
- 8
All classes with the same name reside in a seperate package (different name because they are in a different folder). This way the class becomes unambiguous.
Just be careful in which package you are at the time. in other words be aware you the name resolution technique Java uses.

- 371
- 1
- 2
- 6