Вопрос

If I have two different packages that have classes with the same name, and I want specifically to call class1 from package1 I would use:

import package1.class1;
import package2.*;

But what if I also want all the other classes of package1? Would the correct code be:

import package1.*;
import package2.*;

and then

package1.class1 teste = new package1.class1();

?

Это было полезно?

Решение

If you just import the two packages with a wildcard, you will get a compilation error when trying to use the unqualified class name, as it would be ambiguous:

import package1.*;
import package2.*;

// snipped

// compilation error. 
// No way to tell if you mean package1.class1 or package2.class1
class1 c = new class1(); 

One way around this is to fully qualify your usage:

// No ambiguity, so no error.
package1.class1 c = new package1.class1(); 

Funnily enough, another way around this is to add an additional import for that specific class. This explicit import takes precedence on any wildcard import, and resolves any ambiguity:

import package1.*;
import package2.*;
import package1.class1;

// snipped

// This is an instance of package1.class1.
class1 c = new class1(); 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top