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

Understanding Package Declarations and Imports

Оглавление

Java comes with thousands of built-in classes, and there are countless more from developers like you. With all those classes, Java needs a way to organize them. It handles this in a way similar to a file cabinet. You put all your pieces of paper in folders. Java puts classes in packages. These are logical groupings for classes.

We wouldn't put you in front of a file cabinet and tell you to find a specific paper. Instead, we'd tell you which folder to look in. Java works the same way. It needs you to tell it which packages to look in to find code.

Suppose you try to compile this code:

public class NumberPicker { public static void main(String[] args) { Random r = new Random(); // DOES NOT COMPILE System.out.println(r.nextInt(10)); } }

The Java compiler helpfully gives you an error that looks like this:

error: cannot find symbol

This error could mean you made a typo in the name of the class. You double-check and discover that you didn't. The other cause of this error is omitting a needed import statement. A statement is an instruction, and import statements tell Java which packages to look in for classes. Since you didn't tell Java where to look for Random, it has no clue.

Trying this again with the import allows the code to compile.

import java.util.Random; // import tells us where to find Random public class NumberPicker { public static void main(String[] args) { Random r = new Random(); System.out.println(r.nextInt(10)); // a number 0-9 } }

Now the code runs; it prints out a random number between 0 and 9. Just like arrays, Java likes to begin counting with 0.

In Chapter 5, we cover another type of import referred to as a static import. It allows you to make static members of a class known, often so you can use variables and method names without having to keep specifying the class name.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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