19.1 Packages

Sunday, April 11, 2010 Posted by Sudarsan
Package Examples


Now, let us see some examples related to packages.

All members of the package need to be defined as public, if they need to be accessed from outside.

Example

//Creating a Package

package mypackage;
/**
 *
 * @author Administrator
 */
public class Calculate {
    
    public double volume(double height,double width,double depth)
 {
  return (height*width*depth);
 }
 
 public int add(int x,int y)
 {
  return (x+y);
 }
 
 public int divide(int x,int y)
 {
  return (x/y);
 }

}

Now, we need t o compile this file. For that first create a folder having name same as your package, say, mypackage in this case. Then save “Calculate.java” into this folder. Now compile the file inside the folder by using javac at the command prompt.

Suppose you are working in directory D:\javaprohrams then first create a folder name mypackage into this directory and then save Calculate code file into your foldermypackage.Now change directory to mypackage.

D:\javaprograms\mypackage\javac Calculate.java

To use this package, you need to :
1.Import the class to be used
2.Import the entire package
3.Refer to its members

The fallowing example shows how to use a package

//Using package
//Fully qualified Class Name
Import mypackage.Calculate;

/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        Calculate c=new Calculate();
        
        int sum=c.add(10, 20);
        double vol=c.volume(10.3f, 13.2f, 32.32f);
        int div=c.divide(20, 4);
        
        System.out.println("The Sum is : "+sum);
        System.out.println("The Volume is : "+vol);
        System.out.println("The Division is : "+div);
    }

}

Now compile Main

D:\javaprograms\java Main.java

Then Run

D:\javaprograms\java Main

Then we can see the fallowing output.

The Sum is : 30
The Volume is : 4394.227176385497
The Division is : 5


When compiling a class in package, the javac command-line option -d causes the compiler to create appropriate directories based on the class’s package declaration.The option also specifies where the directories should be stored.

For Example, in a command window, we used the compilation command
javac –d Calculate.java
That’s all folks for this time about packages! Next time we will meet with another topic.
Labels:

Post a Comment