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

Redundant Imports

Оглавление

Wait a minute! We've been referring to System without an import every time we printed text, and Java found it just fine. There's one special package in the Java world called java.lang. This package is special in that it is automatically imported. You can type this package in an import statement, but you don't have to. In the following code, how many of the imports do you think are redundant?

1: import java.lang.System; 2: import java.lang.*; 3: import java.util.Random; 4: import java.util.*; 5: public class NumberPicker { 6: public static void main(String[] args) { 7: Random r = new Random(); 8: System.out.println(r.nextInt(10)); 9: } 10: }

The answer is that three of the imports are redundant. Lines 1 and 2 are redundant because everything in java.lang is automatically imported. Line 4 is also redundant in this example because Random is already imported from java.util.Random. If line 3 wasn't present, java.util.* wouldn't be redundant, though, since it would cover importing Random.

Another case of redundancy involves importing a class that is in the same package as the class importing it. Java automatically looks in the current package for other classes.

Let's take a look at one more example to make sure you understand the edge cases for imports. For this example, Files and Paths are both in the package java.nio.file. The exam may use packages you may never have seen before. The question will let you know which package the class is in if you need to know that in order to answer the question.

Which import statements do you think would work to get this code to compile?

public class InputImports { public void read(Files files) { Paths.get("name"); } }

There are two possible answers. The shorter one is to use a wildcard to import both at the same time.

import java.nio.file.*;

The other answer is to import both classes explicitly.

import java.nio.file.Files; import java.nio.file.Paths;

Now let's consider some imports that don't work.

import java.nio.*; // NO GOOD - a wildcard only matches // class names, not "file.Files" import java.nio.*.*; // NO GOOD - you can only have one wildcard // and it must be at the end import java.nio.file.Paths.*; // NO GOOD - you cannot import methods // only class names

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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