- Java Packages
- Built-in Packages
- Syntax
- Import a Class
- Example
- Example
- Import a Package
- Example
- User-defined Packages
- Example
- MyPackageClass.java
- Using Package Members
- Referring to a Package Member by Its Qualified Name
- Importing a Package Member
- Importing an Entire Package
- Apparent Hierarchies of Packages
- Name Ambiguities
- The Static Import Statement
- How to import all classes at once in eclipse
- Solution:
- Shortcut:
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- How to create simple java project using maven in eclipse
- How to create dynamic web project using maven in eclipse
- How to install maven plugin(m2eclipse) in eclipse
- How to configure Apache Tomcat in eclipse
Java Packages
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:
- Built-in Packages (packages from the Java API)
- User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.
The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class; // Import a single class import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:
Example
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner; class MyClass < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); >>
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign ( * ). The following example will import ALL the classes in the java.util package:
Example
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:
Example
└── root └── mypack └── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack; class MyPackageClass < public static void main(String[] args) < System.out.println("This is my package!"); >>
Save the file as MyPackageClass.java, and compile it:
This forces the compiler to create the «mypack» package.
The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign » . «, like in the example above.
Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called «mypack».
To run the MyPackageClass.java file, write the following:
Using Package Members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one of the following:
- Refer to the member by its fully qualified name
- Import the package member
- Import the member’s entire package
Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Its Qualified Name
So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts . You can use a package member’s simple name if the code you are writing is in the same package as that member or if that member has been imported.
However, if you are trying to use a member from a different package and that package has not been imported, you must use the member’s fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.
You could use this qualified name to create an instance of graphics.Rectangle :
graphics.Rectangle myRect = new graphics.Rectangle();
Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.
Importing a Package Member
To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here’s how you would import the Rectangle class from the graphics package created in the previous section.
Now you can refer to the Rectangle class by its simple name.
Rectangle myRectangle = new Rectangle();
This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.
Importing an Entire Package
To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.
Now you can refer to any class or interface in the graphics package by its simple name.
Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();
The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A .
// does not work import graphics.A*;
Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.
Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square , you could import Rectangle and its nested classes by using the following two statements.
import graphics.Rectangle; import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle .
Another less common form of import , the static import statement, will be discussed at the end of this section.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file).
Apparent Hierarchies of Packages
At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt . However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.
Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color , java.awt.font , or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt , you must import both packages with all their files:
import java.awt.*; import java.awt.color.*;
Name Ambiguities
If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the graphics package defined a class named Rectangle . The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous.
In such a situation, you have to use the member’s fully qualified name to indicate exactly which Rectangle class you want. For example,
The Static Import Statement
There are situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class.
The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,
public static final double PI = 3.141592653589793; public static double cos(double a)
Ordinarily, to use these objects from another class, you prefix the class name, as follows.
double r = Math.cos(Math.PI * theta);
You can use the static import statement to import the static members of java.lang.Math so that you don’t need to prefix the class name, Math . The static members of Math can be imported either individually:
import static java.lang.Math.PI;
import static java.lang.Math.*;
Once they have been imported, the static members can be used without qualification. For example, the previous code snippet would become:
Obviously, you can write your own classes that contain constants and static methods that you use frequently, and then use the static import statement. For example,
import static mypackage.MyConstants.*;
Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read and maintain, because readers of the code won’t know which class defines a particular static object. Used properly, static import makes code more readable by removing class name repetition.
How to import all classes at once in eclipse
Sometimes you copy any java code from somewhere and you see many import errors. You go to each class and press ctrl + space to import each class one by one. Lets say you have large number of classes, you have to import each class one by one.
Solution:
Eclipse have provided organize imports feature which can import all classes at once and prompt you to select any class if there are multiple classes of same name present in classpath.
Right click -> source -> organize imports
Shortcut:
Lets understand with the help of example:
You can see, we need to import lot of classes. Just press ctrl + shift + o, you will see below screen.
Bingo!! you have resolved all import errors at once. I use this shortcut very often, I hope you find it useful.
Was this post helpful?
Share this
Related Posts
Author
Related Posts
How to create simple java project using maven in eclipse
In this post, we will see how to create a simple java project using maven in eclipse. We have already seen before how to create dynamic web project using maven in eclipse. I am using following tools for this post. eclipse-jee-mars-R-macosx-cocoa-x86_64 Apache tomcat 8 m2eclipse plugin jdk 1.7 Steps for creating dynamic web project using maven […]
How to create dynamic web project using maven in eclipse
In this post, we will see how to create dynamic web project using maven in eclipse. If you can also create simple java maven project in eclipse. I am using following tools for this post. eclipse-jee-mars-R-macosx-cocoa-x86_64 Apache tomcat 8 m2eclipse plugin jdk 1.7 Steps for creating dynamic web project using maven in eclipse. 1) Install m2eclipse […]
How to install maven plugin(m2eclipse) in eclipse
Apache maven is a build automation tool used for java projects. It is widely used for building java projects now a days. In this post, we will see how to install m2eclipse maven plugin for eclipse. Steps for installing m2eclipse plugin in eclipse: 1) goto Help->Install new software. 2) Click on add to add m2eclipse […]
How to configure Apache Tomcat in eclipse
Table of ContentsStep 1:Step 2:Step 3:Step 4 :Step 5:Step 6:Step 7: In this post, we will see how to configure apache tomcat in eclipse. As per wikipedia, Apache Tomcat, often referred to as Tomcat, is an open-source web server and servlet container developed by the Apache Software Foundation (ASF). Tomcat implements several Java EE specifications […]