i

JAVA Complete Course

Defining a package

Package in Java programming language is like folder which puts together group of classes, interfaces and sub-packages.

The main usage of packages are:

  • Avoid conflicts in naming. For instance,  there can be more than one classes with name Employee in two packages, college.staff.cse.Employee and university.staff.ee.Employee

  • Searching/Locating and usage of classes, interfaces, enumerations and annotations easier

  • Control the access: protected and default have package level access control which means that protected member is accessible by classes in the same package and its subclasses. A member without any access specifier (also known as default) is accessible by classes in the same package only.

  • Packages can be considered as a tool for data encapsulation

Our responsibility is to put logically connected classes in the same package which in future will help us to find any specific class. Names of packages and general structure of directory are closely related to each other. For example if a package name is department.staff.developers, then there are three directories, department, staff and developers such that developers is present in staff and staff is present department.

Package has following convention of naming: They are named in reverse order of domain names. For example, in a department, the recommended convention is department.staff.developers, department.staff.testers, department.staff.analysts, etc. 

Each Java class must belong to a package. We can explicitly name the package by defining a package statement in the beginning of the java file. If the package statement is skipped, the class belongs to the default package, with no sub-directory structure.

Use of default package is not recommended unless we don’t write toy program or our intention is not quick testing.