** This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details **
Question:
In Python you can do this:
from a import b as c
Copy the code
How do I do this in Java, and I try to import this and I get a conflict
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — the following for the answer, according to support sorting votes — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Answer 1 (528 votes in favor) :
There is no mechanism for aliasing imports in Java, so you can’t give two imported classes the same name without limiting their use. Import a class with a fully qualified name, that is:
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
Copy the code
Answer 2 (77 votes in favour) :
As stated in other answers, Java does not provide this functionality. This feature has been requested several times, such as JDK-4194542: class name alias or JDK-4214789: extended imports allow you to rename imports.
This is not an unreasonable request, it is hardly necessary. Using fully qualified names is not a problem (unless the library does reuse the same simple name, which is bad).
In any case, it doesn’t have the value/cost/value to make a language change.
So, I don’t think we’ll see this feature in Java anytime soon
Answer 3 (67 votes in favour):
It’s worth noting that Groovy has this capability:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Copy the code
Answer 4 (24 votes in favour):
Java does not allow you to do this. You need to refer to one of the classes by its fully qualified name
Answer 4 (Votes for 4):
Java doesn’t have this yet, which is ridiculous. Scala has it:
import com.text.Formatter
import com.json.{Formatter= > JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Copy the code