Packages in Java
Packages in Java correspond with the directory structure in your project. They are used to group and control accessibility of related classes, interfaces and sub-packages.
Why use packages?
The advantages of using packages are:
- Better access control: Packages equip the developer with better access control.
- Avoid name conflicts: Using packages prevents you from running into naming conflicts; for example, if you have a com.admin.User and a com.standard.User classes, you won’t run into a name conflict even though these two classes share the same name.
- Better organization: If you’re working on a very large project, having an organized project structure is a must and packages allow you to neatly organize your project since a package usually contains types that are logically related to one another.
- Packages are defined in all lower case, do not contain special characters (like underscores or other symbols) and don’t contain spaces.
- Typically, companies follow a convention where the package name will start with their organization’s reversed domain name as a unique identifier. If a company name is Supercompany, and one of the projects they have is called CoolApp, then the package name will be com.supercompany.coolapp. All the classes will go into the coolapp directory. This conventions ensures that when you want to share you software (most likely via jar file), using your company domain name in package name will make sure that it is a unique package name; so that when it is ready to be shared and used in other projects, it won’t cause name conflicts.
- Packages are delimited by period (periods are used to indicate sub-packages). So for example, if we have com.supercompany.coolapp.users.SuperUser class; the users package is a sub-package of the coolapp package.
Usages and Examples
In order to use a class from another package, you have to import it. Let’s suppose you want to import the ServiceOne class into your Controller class. If you have the following the structure in your project:
Then in order to retrieve the ServiceOne class in the Controller class, you would have to import it with an import statement like this:
Having that important statement gives you access to the ServiceOne class and allows you to use it in your Controller class. Sometimes, we can have many class inside a package; if you want to import all the classes from a package use the asterisk character in your import statement as such:
The use of the asterisk indicates that all classes and interfaces from the service package will be imported but note that sub-packages of the imported package will not be imported
Test what you’ve learned by answering commonly asked interview questions below!
Common Interview Questions
Q: What is a package and what is it’s purpose?
Q: What is a naming convention for packages?
Q: Does importing packages import its sub-packages?
Hope you learned something!