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?
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.
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.
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.
You can not modify a class after it has been declared and you can not declare two different classes with the same name.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With