Packages

When scripts are written for each Java class, there is a pre-populated line that is present automatically. It is package coreJava. Since we have created a package in Java and placed all the Java classes into that coreJava package, we see it as package coreJava.

Packages are nothing but a set of classes and interfaces. For example, Java comes with a few built-in packages, such as java.length; if we import this package, only then can we access a basic fundamental method, such as public static void main, integer, or array. All these classes come from this java.lang package. It is important to define the package name, because without it, we cannot access the classes present inside the package. This is because java.lang is a default package and it comes within the Java compiler itself.

We have another package as well, java.util. We used this package when we worked on collections; we imported a java.util package. In order to work on ArrayList, this class is present in the java.util package. Therefore, if we remove import java.util.ArrayList, it throws an error because it does not belong to java.lang. All collection interfaces come from the util package.

But how do we know what keyword to use? The following screenshot displays what Eclipse will display if we hover the mouse:

Quick fixes drop down with suggestions to correct the code error

We are importing the java.util package. And from that package, we are importing the ArrayList class. The syntax for it will be:

import package.classname

Here, the reason why we are using ArrayList in this Java class is because we know that ArrayList is in the java.util package. But we need not remember it when we are working with Eclipse. When you just hover the mouse, it suggests we import the package and we can just click on it. It will automatically import that particular test.

HashSet imports the HashSet class from the same util package. If we go to HashMap, it brings HashMap. Thus, whenever we want to work on some tests, we need to import that package or class. System.out.println() also comes from one package only, but they come from java.lang, which is a built-in compiler. These are inbuilt inside the Java packages.

At the same time, we can also define a user-defined Java package. In this case, all our test cases are in a different package called coreJava. If someone wants to use our classes, all they need to do is run import coreJava.classname.

In the next section, we will look at the public modifier. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.252.8