Saturday, November 16, 2013

Packages in Java

Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching, locating and usage of classes, interfaces, enumerations and annotations easier etc. A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.

Creating a package:
When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.

Example:
Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:

/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now put an implementation in the same package animals:
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

No comments:

Post a Comment