Java: import statement vs fully qualified name?

Viewed 20890

I've tried finding an answer to this both online and in my own set of knowledge, but I cannot seem to find a definitive, clear answer.

Suppose I'm using only one class from another package only once which needs to be imported, say myPack.anotherPackage.ClassName.

What is the difference, if any, between using an import statement:

import myPack.anotherPackage.ClassName;

versus using a fully qualified name:

myPack.anotherpackage.ClassName classInst = new myPack.anotherpackage.ClassName();

?

Obviously this question only applies if ClassName is only used once.

7 Answers

The import and package are used for naming and access protection (default) Simple reason for this is there can be many classes with same name.

In order to differentiate between them we need to separate them under packages and import these when required.

There is no difference in importing a class or directly typing fully qualified name, however there are some minute differences. 1. Most importantly if you import all classes in package (i.e. import xyz.*;) The classes can still have naming problem for example if there are multiple general imports you may be using wrong class at runtime.

  1. In case of dynamically loading classes at runtime for example JDBC driver registration at runtime, you need to provide full qualified classname as parameter so it can be loaded dynamically.

In general use following best practice: 1. Never use import abc.*; format of import and always import individual classes (eclipse or some IDE can auto correct imports to * and need to disable this) 2. You have to use fully qualified class name when you have already imported a class of same name and want to use another class with same name under same program. 3. Hope it helps :)

Related