Packages (Java)

What is a Package?


Java allows us to group classes in a collection, known as the Package.


A package is a helpful tool in organizing our work as well as separating our work from the libraries of codes made by others.

The standard Java library is known to have distributed over a number of packages, including the following:


  • java.util
  • java.lang
  • java.net
Reason for Using Packages


The purpose of using packages is to guarantee the uniqueness of class names. Two junior programmers, for example, come up with a good idea of supplying a price class. As long as the two programmers place their class in different packages, there is nothing wrong with it.

The sole purpose of package nesting is to manage their unique names. From the point of view of the complier, there is absolutely no relationship between nested packages. Similar to the packages java.util and java.util.jar both have nothing to do with each other since each has its own independent collection of classes.


Using Packages


A class can use all classes from its own package, including all public classes from other packages. There are indeed two ways to access public class, and those are the following:

1. Add the full package name in front of every class name

java.util.Date today = new java.util.Date();


2. The import keyword

import java.io.*;



The IMPORT keyword


The import statement gives you a shorthand to refer classes in the package. Once you use it, yo no longer have to give the classes their full names.

The * symbol is only used to import a single package. It makes you import the whole package itself.

No comments:

Post a Comment

Extended Search

Custom Search
Hello World