Using Package Members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one of the following:
- Refer to the member by its fully qualified name
- Import the package member
- Import the member's entire package
Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Its Qualified Name
So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts . You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported.
However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.
You could use this qualified name to create an instance of graphics.Rectangle :
Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.
Importing a Package Member
To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here's how you would import the Rectangle class from the graphics package created in the previous section.
Now you can refer to the Rectangle class by its simple name.
This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.
Importing an Entire Package
To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.
Now you can refer to any class or interface in the graphics package by its simple name.
The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A .
Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.
Be aware that the second import statement will not import Rectangle .
Another less common form of import , the static import statement, will be discussed at the end of this section.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file).
Apparent Hierarchies of Packages
At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt . However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.
Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color , java.awt.font , or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt , you must import both packages with all their files:
Name Ambiguities
If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the graphics package defined a class named Rectangle . The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous.
In such a situation, you have to use the member's fully qualified name to indicate exactly which Rectangle class you want. For example,
The Static Import Statement
There are situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class.
The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,
Ordinarily, to use these objects from another class, you prefix the class name, as follows.
You can use the static import statement to import the static members of java.lang.Math so that you don't need to prefix the class name, Math . The static members of Math can be imported either individually:
Once they have been imported, the static members can be used without qualification. For example, the previous code snippet would become:
Obviously, you can write your own classes that contain constants and static methods that you use frequently, and then use the static import statement. For example,
Подключение библиотек в Java

Библиотека — готовый набор классов и компонентов, который встраивают в программу, чтобы реализовать некий функционал. Например, в тысячах казуальных игр музыку можно проигрывать одним и тем же способом. Чтобы не тратить время на работу со звуком, программисту достаточно подключить подходящую библиотеку.
Подключение Джава-библиотек в Eclipse
Если вы пользуетесь средой разработки Eclipse, подключение библиотек в Java займёт у вас меньше минуты:
Разворачиваем дерево проекта в Package Explorer и находим папку libs. Если её нет — создаем.
Кладем нужный .jar в libs.
В появившемся окне выбираем «копирование файлов» (copy files) и жмём OK.
Обновляем проект: правый клик — «Refresh».
Классы подключены и готовы к вызову из нашей программы.
Подключение библиотек Java в Maven и Apache-Ant
Минус подключения библиотек через IDE в том, что для пересборки проекта на другой машине нужна та же среда. Чтобы не зависеть от среды, используют системы сборки Maven и Ant.
Чтобы «прикрутить» библиотеку к проекту Maven, нужно указать её среди зависимостей в файле pom.xml. С библиотекой может подтянуться еще несколько зависимостей, которые подключаются к этой библиотеке. В случае с jar этого не происходит.
Как будет выглядеть наш pom.xml:
Теперь при компиляции проекта библиотека войдет в конечный .jar-файл.
В Ant принцип схожий, но редактировать нужно файл build.xml. Путь к подключаемым библиотекам пишут с помощью тегов <classpath> и <path>. Сначала объясняем, где искать библиотеку:
И далее передаём этот адрес тегу <classpath>:
Как подключить Java-библиотеку вручную
Ваша IDE умеет подключать библиотеки, но как она это делает? Давайте посмотрим, что происходит на уровне файлов. Если библиотека написана на Джаве, её компоненты хранятся либо в архиве .jar, либо в исходниках .java. Более сложный вариант с интеграцией библиотек на C++ пока рассматривать не будем.
Подключение jar-библиотек в Java
Если на компьютере только одна версия Джавы — всё просто. Чтобы подключить .jar, достаточно положить его в папку lib директории Java на жестком диске. Виртуальная машина при ближайшем запуске сама возьмет код из библиотеки.
Когда вы используете одновременно несколько версий Java-машины, раскладывать файлы библиотек для каждой из них утомительно. Лучше указать путь к нужным классам с помощью ключа -classpath.
Открываем терминал и пишем:
java -classpath ./classes ru.аuthor.libname.Main
ru.аuthor.libname.Main — наша библиотека
Точкой перед «/» отмечают текущую директорию.
Можно перечислить несколько библиотек, код из которых компилятор соберет в порядке их перечисления:
java -classpath ./classes;./lib/l1-0.1.jar;./lib/l2-1.5.jar ru. аuthor.libname.Main
Теперь вы умеете подключать библиотеки даже в нестандартной ситуации: когда не установлена IDE или нужно скорректировать очередность подключения.
Как добавить библиотеку (.jar файл) в проект Intellij IDEA
В этой статье мы рассмотрим правильный способ добавления внешней библиотеки ( .jar файла) в проект Intellij IDEA.
Добавляем внешний jar в проект Intellij IDEA
Если вкратце, то вам нужно добавить необходимую библиотеку в модуле зависимостей структуры проекта. А теперь подробнее:
- В открытом проекте, в который нужно добавить библиотеку, нажимаем File и выбираем Project Structure. или же используем горячие клавиши: Ctrl + Alt + Shift + S

File > Project Structure…
2. Далее выбираем пункт Modules и в нем нажимаем на закладку Dependencies . Находим там знак ‘+’ , нажимаем на него и в появившемся блоке выбираем JARs or directories.

Project Settings > Modules > Dependencies > знак ‘+’ > JARs or directories…
3. В появившемся окне выбираем нужный jar файл и нажимаем OK , и еще раз OK в окне подтверждения

И еще раз ОК

Выбор jar > OK > OK
4. Найти только что добавленный jar файл можно в открывающемся списке External Libraries вашего проекта Intellij IDEA.

Стоит заметить, что данные скриншоты подходят для версий Intellij IDEA 14 и 15, в других версиях среды разработки элементы и пункты могут отличаться.