What happens if two packages have the same class name?

When two Java packages contain classes with the same name, the JVM treats them as completely different classes because their fully qualified names are different. However, this can create ambiguity in your code. To avoid confusion, you must reference at least one of the classes using its fully qualified package name.

Key Points:

• Java uniquely identifies a class using its package name and class name together. • Classes with the same name can coexist if they belong to different packages. • You cannot import two classes with the same simple name simultaneously and use them without qualification. • Use the fully qualified class name to resolve naming conflicts. • Proper package naming conventions help minimize such collisions in large applications.

Example:

Suppose a project uses two libraries, and both contain a class named Employee. Java can distinguish them because they belong to different packages, but the developer must explicitly specify which one to use.

Code Example:

import com.company.hr.Employee;

public class Main {

    public static void main(String[] args) {

        Employee hrEmployee = new Employee();

        com.company.payroll.Employee payrollEmployee =
                new com.company.payroll.Employee();
    }
}

Interview Tip:

A concise interview answer is: "If two packages contain classes with the same name, Java identifies them using their fully qualified names. To avoid ambiguity, you must use the package-qualified class name for at least one of the classes when both are used in the same program."