Java Reference
In-Depth Information
the payroll package and the other is in a package named people, the two classes
no longer have a naming conflict. The Employee class in payroll is referred to as
payroll.Employee, while the other class is referred to using people.Employee:
payroll.Employee e1 = new payroll.Employee();
people.Employee e2 = new people.Employee();
In the previous statements, e1 refers to a payroll.Employee object, while e2
refers to a people.Employee object.
Naming Packages
Packages create a namespace, with the name of the package becoming the prefix for the
name of the class. The purpose of a namespace is to avoid naming conflicts where two
classes have the same name.
Suppose that you write a Vehicle class, and I write a Vehicle class. How can we tell them
apart? That's easy if they are in two different packages. For example, I can put my Vehicle
class is in a package named rich:
package rich;
public class Vehicle
{
//My vehicle class
}
Your Vehicle class can be in a different package:
package student;
public class Vehicle
{
//Your vehicle class
}
The name of my Vehicle class is now rich.Vehicle, and the name of your Vehicle class is
now student.Vehicle. The following statements instantiate one of each type:
rich.Vehicle mine = new rich.Vehicle();
student.Vehicle yours = new student.Vehicle();
Of course, this works fine if you and I use different package names; but what if we both
choose rich for the package name? We are then right back where we started with the nam-
ing conflict because both of our classes would be named rich.Vehicle.
Thankfully, this is not a problem in the world of Java development because companies
use a universally agreed-upon naming convention of including the company's Web site
URL as part of the package name. Because Web site URLs are unique, the only possible
naming conflicts that can occur are within a company.
continued
Search WWH ::




Custom Search