Packages
It is an encapsulation mechanism to group related classes and interfaces into a single module. The main purpose of packages are
- To resolve naming conflicts
- To provide security to the classes and interfaces. So that outside person can’t access directly.
- It improves modularity of the application.
There is one universally accepted convention to name packages i.e., to use internet domain name in reverse.
com.icicibank.loan.houseingloan.Account
package com.ashok.helloworld; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
javac HelloWorld.java The generated class file will be placed in current working directory. javac -d . HelloWorld.java -d : Destination to place generated class files . : Current working directory
Generated class file will be placed into corresponding package structure.
- If the specified package structure is not already available then this command itself will create that package structure.
- As the destination we can use any valid directory
E.g
javac -d c: HelloWorld.java
If the specified destination is not available then we will get compilation error
E.g
javac -d z: HelloWorld.java
Here z: is not already available then we will get compile time error
Conclusions
In any java program there should be only at most 1 package statement. If we are taking more than one package statement we will get compile time error.
E.g
package pack1; package pack2; class A { } C.E: class, interface or enum expected
In any java program the first non comment statement should be package statement if it is available.
E.g
import java.util.*; package com.ashok; class A { } C.E: class, interface or enum expected
Packages