How to Import your own Java Package and Use It

How to Import your own Java Package and Use It

There are multiple ways in which we can import or use a package in Java. They are as follows:

  1. Importing all the classes in a package.
  2. Importing only nImpecessary classes in a package.
  3. Specifying the fully qualified name of the class.

First way is to import all the classes in a package using the import statement:

The import statement is placed after the package statement if any and before all class declarations. We can import all the classes in a package as shown below:

import  mypackage.*;

* in the above line denotes all classes within the package mypackage. Now you are free to directly use all the classes within that package. A program which demonstrates importing all classes in a package is given below:

 

If you want to use only one or two classes in a package;

the second way in java:

is to specify the class names instead of * as shown below:

import  mypackage.ClassA;

import  mypackage.ClassB;

A program which demonstrates importing specific class from a package is given below:

 

 

Suppose if two packages contain a class with same name, then it will lead to compile-time errors. To avoid this, we have to use the fully qualified name of the class. A fully qualified name of the class refers to the name of the class preceded by the package name. An example that demonstrates a fully qualified name is given below:

 

Feel free to ask questions about java or share your ideas with us through comment or Contact-Us.

Previous How to Project PC Screen to Mobile Screen
Next How to Group Related Values of Different Data-Types in C++

About author

Raza Bayani
Raza Bayani 42 posts

<p>Raza Bayani studies BCE (Bachelor in Computer Engineering) in Poly-technical University of Kabul. He is the CEO of CODEJOW group, a web designer, coder and recently a blogger. Raza thinks, he can help others and also boost-up his own programming skills being on codejow.com.</p>

View all posts by this author →

You might also like