Recent Posts

Sunday, 26 June 2016

Packages Tutorial


Package
* It is an encapsulation mechanism to group related classes and interfaces into a single module. The main purpose of packages are
1. To resolve naming conflicts
2. To provide security to the classes and interfaces. So that outside person can't access directly.
3. 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
E.g
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 compiletime error

Conclusions
* In any java program there should be only atmost 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

Next Tutorial  Class Modifiers

No comments:

Post a Comment