So what is a Java package and what are the benefits? Great question that you will probably be asked during an interview for a Java position. A package is how a programmer or software developer can organize project files when the project contains multiple modules. A Java package will resolve naming conflicts when different projects have classes with the same name.
- Prevent Naming Conflicts
- Provides Access Control
- Bundle Like Classes and Interfaces
- Re-usability of Code (classes and interfaces)
All related classes and interfaces are put into the same package. Once all of the classes and interfaces are in a package, we can simply import a needed class into our existing program or application. You can think of a package kind of like a directory structure.
Create a Package
The syntax to create a package is simple: package package-name;
Import Class From Package
The syntax to import a package is just as simple: import package-name.class-name
Prevent Naming Conflicts
Outside of organizing, the main benefit of a Java package is avoiding naming conflicts. Let’s look at the two package/import sets below. We can have a package named com.jcd.java.tutorialsOld and another package named com.jcd.java.tutorialsNew and they can both have the same Class called JavaCodeDepotClass. This is only possible with Java Packages.