Package statement in Java

In Java, a package is a way to organize related Java classes within a namespace. It’s like the folders on your computer; instead of putting all Java classes into a single package in a specific folder, we separate them into different packages in different folders. Related Java classes will be in the same package.

We use the keyword package to declare a package. The package name is written in lowercase, and we often use the reverse of the company’s or organization’s domain name to start the package name, for example:

  • com.huongdanjava…
  • com.google…

On your computer, you will see the following folder structure corresponding to the package:

We need package definitions because:

  • Organization: Your application may grow to hundreds or thousands of Java class files. Using packages to organize these Java class files makes them easier to find and maintain.
  • Avoiding name conflicts: You might have two or more libraries defining classes with the same name. Using packages helps identify which class, in which package, you are using.
  • Controlling access: Java access modifiers rely on the package information of classes to determine if a class can access the classes and methods of other classes.
  • Working with import statements: Instead of writing package information along with the class name every time you use a class, you only need to use the import statement to import that class once, and then just use the class name to work with it. The import statement will include information about the package that the class you need to use belongs to.

In short, packages in Java are not just about organizing Java class files; they also help us avoid naming conflicts and implement access control for your Java class files. This makes building and maintaining Java applications much easier.

You can watch the video here:

Add Comment