Thursday 27 March 2014

public access specifier



Above diagram shows the directory structure.
1. Directory named “data_structure” contains two sub directories linear and non-linear. 
2.Directory linear contains two java files named Stack.java, DataStructure.java


package data_structure.linear;

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


package data_structure.linear;

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;
 }
}

Lets say StackTest.java is in the package data_structure.

package data_structure;

import data_structure.linear.*;
class StackTest{
 public static void main(String args[]){
  DataStructure myStack1 = new Stack();
  
  myStack1.delete();
  
  myStack1.insert(10);
  myStack1.insert(20);
  
  myStack1.display();
 }
}




Statements to execute the StackTest.java
C:\>javac -cp . data_structure\linear\DataStructure.java

C:\>javac -cp . data_structure\linear\Stack.java

C:\>javac -cp . data_structure\StackTest.java

C:\>java -cp . data_structure.StackTest
Stack is Empty
10
20


 
As You observe the Stack.java, It is a public class and all the methods in the stack class are public, So from StackTest.java which is completely outside of the package “linear” we accessed the Stack class and and its public methods.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment