1

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();

?

Andy G
  • 19,232
  • 5
  • 47
  • 69
Frank
  • 241
  • 1
  • 2
  • 8
  • 1
    Yes it is the correct way. It was also discussed [here](http://stackoverflow.com/questions/4368120/how-to-use-two-class-with-the-same-name-in-different-packages) – Justas S May 09 '14 at 20:24

1 Answers1

2

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(); 
Mureinik
  • 297,002
  • 52
  • 306
  • 350