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

Wildcards

Оглавление

Classes in the same package are often imported together. You can use a shortcut to import all the classes in a package.

import java.util.*; // imports java.util.Random among other things public class NumberPicker { public static void main(String[] args) { Random r = new Random(); System.out.println(r.nextInt(10)); } }

In this example, we imported java.util.Random and a pile of other classes. The * is a wildcard that matches all classes in the package. Every class in the java.util package is available to this program when Java compiles it. The import statement doesn't bring in child packages, fields, or methods; it imports only classes directly under the package. Let's say you wanted to use the class AtomicInteger (you learn about that one in Chapter 13, “Concurrency”) in the java.util.concurrent.atomic package. Which import or imports support this?

import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*;

Only the last import allows the class to be recognized because child packages are not included with the first two.

You might think that including so many classes slows down your program execution, but it doesn't. The compiler figures out what's actually needed. Which approach you choose is personal preference—or team preference, if you are working with others on a team. Listing the classes used makes the code easier to read, especially for new programmers. Using the wildcard can shorten the import list. You'll see both approaches on the exam.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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