Wednesday 26 March 2014

How to Create a Package

Syntax to Create a package
    package package_name;

for example, you can place all the data structure related classes and interfaces in package named data_structure.

    package data_structure;

Above statement creates a package named data_structure.
The package statement must be the first line in the source file.

Example

package data_structure;

public interface DataStructure{
 int MAX_SIZE = 1000;
 
 void display();
 void insert(int data);
 void delete();
 int search(int data);
}

Create a directory named “data_structure” and place the DataStructure.java file in that. Lets say my “data_structure” directory in C:\packages\.

javac -cp . data_structure\DataStructure.java


 
The -cp option sets the classpath. . means "the current directory". Normally, if you do not have the CLASSPATH environment variable set, the current directory is automatically in the classpath. But if you've set CLASSPATH and didn't add the current directory explicitly, it won't work.

Use the above command to compile the file

Lets say there is a class Stack, which implements the DataStructure interface.


package data_structure;

public class Stack implements DataStructure{
 int top = -1;
 
 int stack[] = new int[DataStructure.MAX_SIZE];
 
 public void display(){
  for(int i=0; i<=top; i++){
   System.out.println(stack[i]);
  }
 }
 
 public void insert(int data){
  if(top < DataStructure.MAX_SIZE-1){
   top++;
   stack[top] = data;
  }
  else{
   System.out.println("Stack is not empty");
  }
 }
 
 public void delete(){
  if(top == -1){
   System.out.println("Stack is Empty");
  }
  else{
   stack[top] = 0;
   top--;
  }
 }
 
 public int search(int data){
  for(int i=0; i < top; i++)
   if(stack[i] == data)
    return 0;
  return -1;
 }
}
Use the below command to compile the class “Stack.java”
    javac -cp . data_structure\Stack.java


  
How to use the packages
We can import a package by using import statement.
    import package.*;
Example
  import data_structure.*; 


import data_structure.*; 
class StackTest{
 public static void main(String args[]){
  DataStructure myStack1 = new Stack();
  
  myStack1.delete();
  
  myStack1.insert(10);
  myStack1.insert(20);
  
  myStack1.display();
 }
}
 
Lets say myStackTest.java” is in C:\packages
    javac StackTest.java


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment