Package in Java
Package in Java
Package in Java
PACKAGES
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
Preventing naming conflicts. For example there can be two classes with name
Employee in two packages,
college.staff.cse.Employee
college.staff.eee.Employee
19/11/2023 2
PACKAGES
19/11/2023 3
PACKAGES
All we need to do is put related classes into packages. After that, we can
simply write an import class from existing packages and use it in our
program.
We can reuse existing classes from the packages as many time as we need
it in our program.
19/11/2023 4
How packages work?
Package names and directory structure are closely related.
19/11/2023 5
Types of packages:
19/11/2023 6
Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
19/11/2023 7
Built-in Packages
4)java.applet: Contains classes for creating Applets.
19/11/2023 8
User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being
the package names.
19/11/2023 9
User-defined packages
19/11/2023 10
User-defined packages
19/11/2023 11
19/11/2023 12
19/11/2023 13
19/11/2023 14
Important points:
Every class is part of some package.
If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
If package name is specified, the file must be in a subdirectory called name (i.e.,
the directory name must match the package name).
We can access public classes in another (named) package using: package-
name.class-name
19/11/2023 15