Course contentsShow
← Java
Lesson 677 of 2,87016. Packages, Imports, and JAR FilesFree lesson

Using FQNs to Resolve Name Conflicts

Understand how FQNs allow using classes with identical names from different packages.

Using FQNs to Resolve Name Conflicts

What you'll learn: How to use fully qualified names (FQNs) to work with classes that have the same simple name but come from different packages.


The Problem: Name Collisions

Sometimes you'll need to use two classes with identical names from different packages in the same file. For example, both java.util.Date and java.sql.Date exist in Java. If you import one, you can't import the other with a simple import statement—Java won't know which one you mean when you write Date.

The Solution: Use FQNs

When you have a name conflict, you can use the fully qualified name for one or both classes. This means writing out the complete package path and class name every time you reference the class.

import java.util.Date;  // Import one normally

public class Example {
    public void processDate() {
        Date utilDate = new Date();  // Uses java.util.Date
        
        // Use FQN for the conflicting class
        java.sql.Date sqlDate = java.sql.Date.valueOf("2024-01-15");
    }
}

How It Works

By writing java.sql.Date, you're being explicit about exactly which Date class you mean. The compiler doesn't need to guess or rely on imports—the full path tells it precisely where to find the class.

You can also skip imports entirely and use FQNs for everything, though this makes code more verbose:

public class Example {
    public void processDate() {
        java.util.Date utilDate = new java.util.Date();
        java.sql.Date sqlDate = java.sql.Date.valueOf("2024-01-15");
    }
}

Key Takeaway: When two classes share the same simple name, use fully qualified names (FQNs) to explicitly specify which class you're referencing, eliminating ambiguity and allowing both classes to coexist in your code.