Difference between normal import & static import?
Explain import statement and difference between normal import & static import?
To access a class or method from another package we need to use the fully qualified name or we can use import statements. The class or method should also be accessible. Accessibility is based on the access modifiers. Private members are accessible only within the same class. So you won’t be able to access a private member even with the fully qualified name or an import statement. It must be noted that the import statement is optional. At any place where you use a class name, you can use its fully qualified name, that includes its full package hierarchy
- java.util.ArrayList a=new java.util.ArrayList
- The problem with uses of the fully qualified name every time is it increases of the length of the code and reduces readability.
- We can solve this problem by using the import statement.
- Whenever we are writing import statement it is not required to use fully qualified name every time we can use short name directly
There are two type of import statement:-
- Explicit class import:-Â It is highly recommended to use explicit class import because it improves readability of the code
- Implicit class import:-Â Not recommend to use because it reduces the readability of the code.
- While resolving class name compiler will always give the precedence in the following order.
- Explicit class import
- Classes present in the current working directory(Default package)
- Implicit class import
- Whenever we are importing a java package all classes and interfaces present in that package by default available but not sub-package classes. If you want to subpackage class compulsory we should write import statement until sub-package level.
- The import statement is totally compiled time-related concept. If more no of imports then more will be compile time but there is no effect on execution time(Runtime).
- Difference between C language and java language import statement.
- In the case of c language #include, all input-output header files will be loaded at beginning only(At translation time). Hence it is static include.
- In the case of java import statement, no .class file be loaded at the beginning. Whenever we using a particular class then only corresponding .class file be loaded. This is like dynamic include or load on demand.