Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Name of Import in Java, or import two classes with the same name

Tags:

java

import

In Python you can do a:

from a import b as c 

How would you do this in Java, as I have two imports that are clashing.

like image 802
Federer Avatar asked Mar 15 '10 14:03

Federer


People also ask

Can 2 classes have same name in Java?

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 create two classes with 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.

What are the two types of import statement in Java?

There are two types of import Explicit & Implicit, well what is import and why do we need to use in our java source code? When we use predefined java classes in our java code then we need to load that class by the using import keyword at the very first line of our program.

Can we give fully qualified class name instead of importing that class if yes how do you do that?

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.


1 Answers

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;  private Formatter textFormatter; private com.json.Formatter jsonFormatter; 
like image 154
Bozho Avatar answered Oct 11 '22 14:10

Bozho