Packages in java help in grouping related classes and help differentiate classes with same name belonging to different areas. These reduce the complexity of naming the classes, otherwise the class names might get unusually long and ugly. As we know that every class name has to be unique in the application.
// File : com\naturalresources\Light.java
package com.naturalresources;
class Light
{
double frequency;
double wavelength;
}
// File : com\electrical\home\Light.java
package com.electrical.home;
class Light
{
double wattage;
double price;
String color;
}
Here we have created two classes both with same name
Light
. One class is in the package
com.naturalresources
where as the other
Light
is in the package
com.electrical.home
.
Please note the following rules about packages:
- One .java file can contain only the classes belonging to one package. And they should be placed in the same directory structure as per the package name specified. e.g., If the sources directory is D:\sources, then the first Light.java file should be placed in D:\sources\com\naturalresources directory, where as the second Light.java should be placed in D:\sources\com\electrical\home directory.
- The complete class name including the package name should be used while creating the object of that class.
// Creating the natural resources Light
com.naturalresouces.Light naturalLight = new com.naturalresouces.Light();
System.out.println("Frequency of natural Light : " + naturalLight.frequency);
// Creating the electrical Light
com.electrical.home.Light electricLight = new com.electrical.home.Light();
System.out.println("Wattage of Electric Light : " + electricLight.wattage);
- If we are only using one of the
Light
classes, then we can import that class using the import
keyword. Then it is not necessary to qualify the class with the package
name in that program.
import com.electrical.home.Light;
...
// Since electrical light is imported, it will by default point to imported Light class
Light light = new Light();
System.out.println("Wattage of Electric Light : " + light.wattage);
- Multiple classes belonging to the same package can be imported using star/asterisk (
*
). If there were multiple classes like Light
, Fan
and Geyser
present in the com.electrical.home
package, then all of them can be imported using the *
as shown below.
import com.electrical.home.*;
...
Light light = new Light();
Fan fan = new Fan();
Geyser geyser = new Geyser();