Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 76

Naming Conflicts

Оглавление

One of the reasons for using packages is so that class names don't have to be unique across all of Java. This means you'll sometimes want to import a class that can be found in multiple places. A common example of this is the Date class. Java provides implementations of java.util.Date and java.sql.Date. What import statement can we use if we want the java.util.Date version?

public class Conflicts { Date date; // some more code }

The answer should be easy by now. You can write either import java.util.*; or import java.util.Date;. The tricky cases come about when other imports are present.

import java.util.*; import java.sql.*; // causes Date declaration to not compile

When the class name is found in multiple packages, Java gives you a compiler error. In our example, the solution is easy—remove the import java.sql.* that we don't need. But what do we do if we need a whole pile of other classes in the java.sql package?

import java.util.Date; import java.sql.*;

Ah, now it works! If you explicitly import a class name, it takes precedence over any wildcards present. Java thinks, “The programmer really wants me to assume use of the java.util.Date class.”

One more example. What does Java do with “ties” for precedence?

import java.util.Date; import java.sql.Date;

Java is smart enough to detect that this code is no good. As a programmer, you've claimed to explicitly want the default to be both the java.util.Date and java.sql.Date implementations. Because there can't be two defaults, the compiler tells you the imports are ambiguous.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх