5) Packages
Last updated
Last updated
Use a package to group together a related set of classes and interfaces.
You can indicate that a class or an interface is defined in a package by using the package statement as the first statement in code.
A package is made of multiple sections that go from the more-generic (left) to the more-specific (right).For example:
Ex 2:
Per Java naming conventions, package names should all be in lowercase.
The package and subpackage names are separated using a dot (.).
Package names follow the rules defined for valid identifiers in Java.
For classes and interfaces defined in a package, the package statement is the
first statement in a Java source file (a .java file). The exception is that comments
can appear before or after a package statement.
There can be a maximum of one package statement per Java source code file
(.java file).
All the classes and interfaces defined in a Java source code file are defined in
the same package. They can’t be defined in separate packages.
The import statement enables you to use simple names instead of using fully qualified names for classes and interfaces defined in separate packages.
Problem statement: Need to access living room of home from office cubicle.
Solution:
Explanation:
To refer to the LivingRoom in Cubicle, you must specify its complete location, as shown in the left part of the figure. As you can see in this figure, repeated refer- ences to the location of LivingRoom make the description of LivingRoom look tedious and redundant. To avoid this, you can display a notice in Cubicle that all occurrences of LivingRoom refer to LivingRoom in Home and thereafter use its simple name. Home and Office are like Java packages, and this notice is the equivalent of the import statement.Above figure shows the difference in using fully qualified names and simple names for LivingRoom in Cubicle.
One way (Left part of figure)
Second way (Right part of figure)
Importing a single member versus all members of a package:
By using the wildcard character, an asterisk (*), you can import all the public members, classes, and interfaces of a package.
Let say we have 2 classes ExamQuestion and MultipleChoice in package certification.