Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import two classes with the same name in different packages?

I want to import these two classes, both named Query - one a JDO class, the other a JPA class, to use in different methods in the same class.

import javax.jdo.Query;
import javax.persistence.Query;

Is there a way to globally import both of them at the same time at the top of the file?

like image 932
Ment Avatar asked Sep 16 '10 21:09

Ment


People also ask

Can two classes in different packages have the same name?

Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two import statements. You'll have to fully qualify one of the class names if you really need to reference both of them.

Can I import two classes with same name in Java?

One would have the same problem importing those classes in Java code. It's just not possible to import two classes with the same name, because there is no way to tell which one you are referring to when you use the class' name only (e.g. (Application.)). (Application.) (javafx.

Can we have multiple Java classes with the same name in the same package?

A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.

Can we declare two classes with same name?

You can not modify a class after it has been declared and you can not declare two different classes with the same name.


2 Answers

I'm afraid, no. But you don't have to import class to use it: just reference one of the classes by its full name, like

javax.jdo.Query query = getJDOQuery();
query.doSomething();

Then you can import another without name collisions.

BTW, sometimes if you start getting lots of such name such collisions in your class, it's a subtle hint for refactoring: splitting functionality of one big class between several small ones.

like image 89
Nikita Rybak Avatar answered Sep 30 '22 22:09

Nikita Rybak


The existing answers are correct. I'd like to show you how class name conflicts can be handled in Kotlin (docs).

If there is a name clash, we can disambiguate by using as keyword to locally rename the clashing entity:

import javax.jdo.Query // Query is accessible
import javax.persistence.Query as jpaQuery // jpaQuery stands for 'javax.persistence.Query'

That's +1 reason why you should consider Kotlin for your next project.

like image 35
naXa Avatar answered Sep 30 '22 22:09

naXa