Introduction to Java
Java packages are a mechanism to organize Java classes into namespaces. It helps to avoid naming conflicts between classes and to provide a way to reuse code. In this lesson, we will cover the following topics about Java packages:
- Creating packages in Java;
- Accessing classes from different packages;
- Importing classes from different packages;
- Using sub-packages;
- Package naming conventions.
Creating packages in Java
To create a package in Java, you need to add a package statement at the beginning of the Java source file before any import statements. The syntax for creating a package is as follows:
For example, if you want to create a package named
com.example, the statement would look like this:
Once you have added the package statement, you can define classes inside the package. Moreover, you can have multiple classes in a single package.
Accessing classes from different packages
To access classes from a different package, you need to use the fully qualified name of the class. The fully qualified name of a class includes the package name and the class name, separated by a dot. For example, if you have a class named
MyClass in the
com.example package, you can access it using the following syntax:
Importing classes from different packages
To avoid having to use the fully qualified name every time you want to access a class from a different package, you can use the import statement. The syntax for importing a class is as follows:
For example, to import the
MyClass class from the
com.example package, you can use the following statement:
Once you have imported the class, you can use its name without the package name, like this:
You can also organize classes into sub-packages. To create a sub-package, add another level to the package name.
For example, if you have a package named
com.example, you can create a sub-package named
To access a class in a sub-package, you can use the fully qualified name or import the class using the import statement.
Package naming conventions
It is a good practice to follow some naming conventions when creating packages. The most common convention is to use a reverse domain name as the prefix for the package name.
For example, if your domain name is
example.com, you can create a package named
This naming convention helps avoid naming conflicts with other packages and clarifies where the package came from.
In conclusion, Java packages are useful for organizing Java code and avoiding naming conflicts. Following some naming conventions can make your packages more readable and maintainable.
What is the syntax to create a package in Java?
Select the correct answer
What is the purpose of using the import statement in Java?
Select the correct answer