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

Packages

Оглавление

As you saw in the previous example, Java classes are grouped into packages. The import statement tells the compiler which package to look in to find a class. This is similar to how mailing a letter works. Imagine you are mailing a letter to 123 Main Street, Apartment 9. The mail carrier first brings the letter to 123 Main Street. Then the carrier looks for the mailbox for apartment number 9. The address is like the package name in Java. The apartment number is like the class name in Java. Just as the mail carrier only looks at apartment numbers in the building, Java only looks for class names in the package.

Package names are hierarchical like the mail as well. The postal service starts with the top level, looking at your country first. You start reading a package name at the beginning too. For example, if it begins with java, this means it came with the JDK. If it starts with something else, it likely shows where it came from using the website name in reverse. For example, com.wiley.javabook tells us the code is associated with the wiley.com website or organization. After the website name, you can add whatever you want. For example, com.wiley.java.my.name also came from wiley.com. Java calls more detailed packages child packages. The package com.wiley.javabook is a child package of com.wiley. You can tell because it's longer and thus more specific.

You'll see package names on the exam that don't follow this convention. Don't be surprised to see package names like a.b.c. The rule for package names is that they are mostly letters or numbers separated by periods (.). Technically, you're allowed a couple of other characters between the periods (.). You can even use package names of websites you don't own if you want to, such as com.wiley, although people reading your code might be confused! The rules are the same as for variable names, which you see later in this chapter. The exam may try to trick you with invalid variable names. Luckily, it doesn't try to trick you by giving invalid package names.

In the following sections, we look at imports with wildcards, naming conflicts with imports, how to create a package of your own, and how the exam formats code.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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