Wednesday, 22 January 2014

PACKAGES AND INTERFACES

PACKAGES

Packages in java with example program

Packages are containers for classes. Packages help in avoiding naming conflicts.A package defines a name space for a set of classes that are related to each other. The name space defined by a package ensures that there are no two classes with the same name. But two packages can have a class with the same name without any name collision among them.We can define classes inside a package that are not accessible by code outside that package.One can also define class members that are only exposed to other members of the same package. This allows your classes to have intimate knowledge of each other, but not exposing that knowledge to the rest of the world.

Defining a Package


To create a package just simply include a package command as the first statement in a Java Source file. Any classes declared within that file will belong to the specified package.

This is the general form of the package statement :

  package pkg;

          here, pkg is the name of the package.

 For example, the following statement creates a package called MyPackage.

  package MyPackage;


The package statement simply specifies to which package the classes defined the file belong.

Java uses file system directories to store packages. That is, those .class files which we want them to be part of MyPackage must be stored in a directory called MyPackage.

Short package Example:

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();
   }
Now, you compile these two files and put them in a sub-directory called animals and try to run as follows:

$ mkdir animals
$ cp Animal.class  MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels





No comments:

Post a Comment