Sub topic 9
Resolving Name Conflicts
This chapter assumes you can declare a package, write single-type and wildcard imports, and compile a multi-package program with javac -d. Packages exist so that two classes can share a simple name without clashing. The conflict appears when one source file needs to use both classes, or when the compiler has to pick one of several classes that could match a name you wrote.
What a conflict looks like
A simple name such as Date or List is only a shorthand. The compiler expands it to a fully qualified name, such as java.util.Date, by searching a fixed set of places. A conflict happens in one of two ways:
- Two classes match the same simple name at the same priority level, so the compiler cannot choose. This is an ambiguity error.
- A class matches at a higher priority than the one you meant, so the compiler silently picks the wrong one. This is shadowing.
Ambiguity is the easier problem because the compiler reports it. Shadowing can change what your program does without any error.
The first tool: fully qualified names
A fully qualified name is always unambiguous. You can use one class through an import and write the other with its full name:
import java.util.Date;
public class DateConflict {
public static void main(String[] args) {
Date utilDate = new Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(utilDate.getTime() == sqlDate.getTime());
}
}This prints true. The simple name Date refers to java.util.Date because of the import. java.sql.Date is spelled out in full wherever it appears.
Choose one class to import, normally the one you use most in the file, and qualify the other. If you need both many times, a better fix is often to move the code that touches one of them into a separate class.
Java has no import aliases. Some languages let you write import X as Y, but Java does not. Fully qualifying the name is the only way to use two same-named classes in one file.
The order in which simple names are resolved
When the compiler meets a simple type name, it looks in this order and stops at the first level that has a match:
- Types declared in the same source file, and types brought in by single-type imports. A clash within this level is an error.
- Other types in the same package, including those in other files.
- Types brought in by on-demand (wildcard) imports. The implicit
import java.lang.*;belongs to this level.
Local variables, fields and nested types are resolved by separate rules. Those rules apply before any of the levels above, as covered in the "Variables can hide types and packages" section later in this chapter.
The table below turns these levels into a rule of thumb for each combination.
| Situation | Result |
|---|---|
| Two single-type imports with the same simple name but different types | Compile error at the second import |
| Single-type import and a class of the same name declared in the same file | Compile error |
| Single-type import and a class of that name in the same package (another file) | The import wins |
| Class in the same package and a wildcard import of that name | The same-package class wins |
| Two wildcard imports that both contain the name | Error only if you use the name |
| Wildcard import and `java.lang` both contain the name | Ambiguity error if you use the name |
Ambiguity from wildcard imports
Two wildcard imports are legal even when both packages contain a class with the same name. The error appears only where you use that name:
import java.util.*;
import java.sql.*;
public class Ambiguous {
public static void main(String[] args) {
Date d = new Date();
}
}The compiler rejects this with a message like reference to Date is ambiguous, followed by a note that both java.util.Date and java.sql.Date match. The classic version of the same mistake is import java.util.*; together with import java.awt.*;, where List matches both java.util.List and java.awt.List.
The fix is to add a single-type import, because that sits at a higher level than any wildcard:
import java.util.*;
import java.sql.*;
import java.util.Date;
public class Fixed {
public static void main(String[] args) {
Date d = new Date(0);
System.out.println(d.getTime());
}
}This prints 0. The wildcard imports still work for every other class in both packages. The single-type import settles only the Date conflict.
Wildcards can break code later
A wildcard import accepts any class the package contains, now or in the future. If a library or JDK release adds a class whose name matches one from another wildcard package that you use, code that compiled before can fail with an ambiguity error. Single-type imports do not have this problem, which is one reason many teams prefer them in long-lived code.
Shadowing by classes in your own package
A class in your own package beats a wildcard import and beats java.lang. Consider a package that defines its own List:
package com.example.report;
public class List {
public String describe() {
return "report list";
}
}A second class in the same package imports java.util.* and uses List:
package com.example.report;
import java.util.*;
public class Report {
public static void main(String[] args) {
List mine = new List();
java.util.List<String> names = new ArrayList<>();
names.add("x");
System.out.println(mine.describe() + " " + names);
}
}This prints report list [x]. The simple name List means com.example.report.List, even though java.util.* is imported and contains a List too. There is no error and no warning. To get the JDK type, you must qualify it, as the second line of main does, or write import java.util.List;. A single-type import overrides the same-package class.
The same rule applies to java.lang. If you declare a class named String or Object in your package, every file in that package sees your class under that name. This is a common source of confusing errors in beginner projects.
Declaring a class with a name that you also import by a single-type import in the same file is different. It is an error, because both live at the first level:
import java.util.List;
public class List { }The compiler reports that List is already defined in this compilation unit.
Static import conflicts
Static imports follow similar rules, with one extra twist for methods. Two static imports of methods with the same name are allowed, and Java treats them as overloads. The compiler then chooses by argument types, as it does for any overloaded call. Two static imports of fields with the same name conflict, and the error appears only when you use the name.
A method you declare in your own class shadows every statically imported method of the same name, even when the parameter types differ:
import static java.lang.Math.max;
public class Shadow {
static int max(int a) {
return a;
}
public static void main(String[] args) {
System.out.println(max(3, 7));
}
}This does not compile. The call max(3, 7) looks only at methods named max declared in Shadow, and finds one with a single parameter. The imported Math.max is hidden. Rename your method or call Math.max(3, 7) explicitly.
Variables can hide types and packages
Name resolution also treats a name used in an expression differently from a name used as a type. If a variable and a type share a name, the variable wins. A variable also beats a package of the same name. For example, a local variable called java makes java.util.List stop working in that scope. These cases are rare in code that follows Java naming conventions. Class names start with an uppercase letter and variables with a lowercase one, which is why the conventions matter.
A practical checklist
Work through these steps when a name does not resolve the way you expect:
- Read the full error. Ambiguity errors list the competing fully qualified names.
- Check whether your own package declares a class with that name. If so, it may be shadowing an imported one.
- Prefer a single-type import for the class you use most, and write the other one fully qualified.
- Replace the offending wildcard import with the specific imports you need.
- Use your IDE's "organize imports" feature, which resolves most of these cases for you. Review what it chose when two candidates exist.
Exercise
A file contains import java.util.*; and import java.awt.*; and uses List<String> names;. It fails to compile. Give two different fixes, and say why each one works.
Show answer
Fix 1: add import java.util.List;. A single-type import has higher priority than any wildcard, so List now means java.util.List. Fix 2: write java.util.List<String> names; with the fully qualified name, which needs no lookup. Replacing the wildcards with only the specific classes needed also works, because then only one List can match.
Exercise
The package com.example.report contains a class List. Another class in the same package has import java.util.*; and declares List<String> names = new ArrayList<>();. Does this compile, and if not, why not?
Show answer
It does not compile. The simple name List resolves to com.example.report.List, because a class in the same package beats a wildcard import. That class is not generic, so List<String> is an error, and it is not assignable from ArrayList. Add import java.util.List; or write java.util.List<String>.