Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 78
Creating a New Package
ОглавлениеUp to now, all the code we've written in this chapter has been in the default package. This is a special unnamed package that you should use only for throwaway code. You can tell the code is in the default package, because there's no package name. On the exam, you'll see the default package used a lot to save space in code listings. In real life, always name your packages to avoid naming conflicts and to allow others to reuse your code.
Now it's time to create a new package. The directory structure on your computer is related to the package name. In this section, just read along. We cover how to compile and run the code in the next section.
Suppose we have these two classes:
package packagea; public class ClassA {} package packageb; import packagea.ClassA; public class ClassB { public static void main(String[] args) { ClassA a; System.out.println("Got it"); } }
When you run a Java program, Java knows where to look for those package names. In this case, running from C:\temp
works because both packagea
and packageb
are underneath it.