Same class name in different packages
i was taken to this page by google when i had the error a type with the same simple name is already defined by the single-type-import
. i fixed this error (AFTER A VERY LONG TIME) by realising the line import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
had snuck into the very top of my imports whilst i had the line import org.apache.commons.codec.binary.Base64;
at the bottom of my imports.
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.
Example: Suppose you have
pkg1/SomeClass.java
package pkg1;
public class SomeClass {
}
pkg2/SomeClass.java
package pkg2;
public class SomeClass {
}
and Main.java
import pkg1.SomeClass; // This will...
import pkg2.SomeClass; // ...fail
public class Main {
public static void main(String args[]) {
new SomeClass();
}
}
If you try to compile, you'll get:
$ javac Main.java
Main.java:2: pkg1.SomeClass is already defined in a single-type import
import pkg2.SomeClass;
^
1 error
This however does compile:
import pkg1.SomeClass;
public class Main {
public static void main(String args[]) {
new SomeClass();
new pkg2.SomeClass(); // <-- not imported.
}
}
Sure can but you'll need to distinguish which one you want when calling them in other packages if both are included within a source file.
Response to Comment:
com.test.package1.Foo myFoo = new com.test.package1.Foo();
com.test.package2.Foo myOtherFoo = new com.test.package2.Foo();