In this tutorial, let’s learn how to define, the directory structure corresponding to the package in Java.
Package in Java is used to group classes or interfaces that share some common points. We can define multiple packages in our project according to purpose.
We can use the package statement to define what our class or interface is in.
In the example above, I have defined the Student class in the com.huongdanjava package. We can use such package names for small projects, but for the standard, Oracle encourages us to define the following:
- com.huongdanjava: is the name of the internet domain of the company has reversed.
- ocaexample: is the current project name that the company owns.
- entity: is the service within the project.
Some of the rules that we need to take into account when defining a package are:
- The package name should be defined in lowercase.
- Package and child packages are separated by a dot.
- The package statement used to define a package must be declared first in the Java file unless the comments can be defined before or after the package statement.
- We can only define a package statement in a Java file.
- Classes and interfaces defined in the same Java file are in the same package.
- If we do not define a package for our Java class, then by default this class will be in the default package.
The directory structure corresponds to the package name
In the above example, we have defined the package name com.huongdanjava corresponding to the directory structure that will be com/huongdanjava. Our Student class will be in the huongdanjava directory, as follows:
For a class that defines the default package, that class will be located in the src directory of our project.
The example class defines it with the default package:
In the project structure, it will be in the default package:
And in the directory, it will be in the src directory: