Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Importing Classes & Packages


If you're wondering what does importing a class mean, then it simply means making a class available to your current class.

Java provides import statement to import classes.
Following examples show usage of import statement:
   import myPackage.myClass;
   import myPackage1.myPackage2.myClass;
   import myPackage.*;

If you don't use import; then also you can access any class from any package in your code (if allowed by corresponding access specifiers). You'll have to refer to fully qualified name of the class throughout your code. For e.g. if there is no import statement for myPackage1.myPackage2.myClass; then you would need to write myPackage1.myPackage2.myClass everytime you want to use myClass in your code. So, import statement actually provides convenience in terms of writing code as well as reviewing code.
In short, once you've imported a class, you don't need to write it's fully qualified name everytime; only class name would suffice.

Following points are worth keeping in mind:
- import statement comes immediately after package statement (if any).
- You can import as many classes/packages as you want. There is no limit to the no. of import statements.
- When using * in import statement; it will import all the public classes of specified package in current current class. This also means that if you're importing a large package, then your compilation time met get increased; however during runtime JVM would refer to only those classes that are actually being used, so runtime behaviour would not be affected at all.
- If there are two classes with same name in different packages, then also compiler would be able to successfully compile the code; however, during runtime JVM would throw an error because it won't be able to decide which class to use. In this case, you must provide fully qualified name of the class being used. - By default, if two classes exist in same package, then they can refer each other directly.
- java.lang package is by default imported in all classes.


 

If you don't use import; then also you can access any class from any package in your code (if allowed by corresponding access specifiers). You'll have to refer to fully qualified name of the class throughout your code. For e.g. if there is no import statement for myPackage1.myPackage2.myClass; then you would need to write myPackage1.myPackage2.myClass everytime you want to use myClass in your code. So, import statement actually provides convenience in terms of writing code as well as reviewing code.