Java Packages
Java Packages
Packages are convenient for organizing our work and for separating our work
from code libraries provided by others. The standard Java library is distributed
over two main packages ‘java’ and ‘javax’.
2) Packages can contain hidden classes not visible outside the packages.
Package Contents
name
java.lang It contains the language support classes. These are classes
that java compiler itself uses and therefore they are
automatically imported.
1) Declare the package at the beginning of a file using the keyword package
followed by a package name.
package mypackage;
2) Define the class that is to be put in the package and declare it public.
package mypackage;
3) This source file has to be saved as a file with name FirstClass.java and
located in a subdirectory named ‘mypackage’ under the directory where the
working source files are stored.
Accessing a Package
A class can use all classes from its own package and all public classes from
other packages.
The public classes in another package can be accessed in two ways. The first is
simply to add the full package name in front of every class name.
For example:
The second way is to use import statement. The point of the import statement
is simply to give shorthand to refer to the classes in the package. Once the
import is used, the classes have no longer been given their full names. Specific
classes or the whole package can be imported using import keyword. The
import statement should be placed at the top of the source file but below any
package statements.
For example:
Or
An Example
First.java (should be saved in mypackage subdirectory)
package mypackage;
}
}
import mypackage.First;
f.display();
}
}
package mypackage;
--------
--------
Hiding Classes
When a package is imported using asterisk (*), all public classes are imported.
However, the classes that are not declared public are not imported. This allows
hiding these classes from accessing from outside of the package.
Example:
package package1;
class Second
{
//body of Second
}
-----
import package1.*;
Static Imports
Starting with Java SE 5.0, the import statement has been enhanced to permit
the importing of static methods and fields, not just classes.
is added to the top of the source file, then static methods and fields of the
System class can be used without the class name prefix:
If a static import is used for Math class, the math functions can be used in a
more natural way. For example,
sqrt(pow(x,2) + pow(y,2))