You are on page 1of 12

Packages

Defining a Package
Package: It arranges classes, interfaces, and sub packages into
a particular group.

2 types: pre-defined and user-defined.

The general form of the package statement:


package pkg;

Example –
package mypackage;
package mypackage;

public class Simple{


public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Advantages of Package
1) used to categorize the classes and interfaces so that they
can be easily maintained.

2) provides access protection.

3) removes naming collision.


● We can create a hierarchy of packages

package pkg1[.pkg2[.pkg3]];
Example:
package java.awt.image;
Class path
1. The Java run-time system uses the current working
directory as its starting point.

2. We can specify a directory path or paths by setting the


CLASSPATH environmental variable.

3. Use the -classpath command-line option with java and


javac to specify the path to your classes.

Example: javac –classpath


C:\MyPrograms\Java\mypackage Simple.java
Finding Packages and CLASSPATH
package mypackage;
class Test {
int a, b;
Test(int x, int y) {
a = x; b = y;
}
void display() {
System.out.println("a= "+a+" b= "+b);
// Path here is: mypackage.PackageDemo
}
}
public class PackageDemo {
public static void main(String args[]) {
Test test = new Test(2,3);
test.display();
}
}
// A simple package
package mypackage;
class Balance {
String name;
double balance;
Balance(String name, double balance) {
this.name = name;
this.balance = balance;
}
void show() {
if( balance < 0 ) {
System.out.print("--> ");
}
System.out.println(name + ": $" + balance);
}
}
public class AccountBalance {
public static void main(String args[]) {
Balance accounts [] = new Balance[3];
accounts [0] = new Balance("K. J. Fielding", 123.23);
accounts[1] = new Balance("Will Tell", 157.02);
accounts [2] = new Balance("Tom Jackson", -12.33);
for(Balance account: accounts) account.show();
}
}
Access Protection
Importing Packages

● import pkg1[.pkg2].(classname|*);

● Example
● import java.util.Date; // import Date class under java.util
● import java.io.*; // import all classes under java.io
Lab Activity/Exercise 21
Develop a JAVA program to create a package called
mypackage. Define a class in mypackage. Import the
same class with a suitable import statement and test it
in a main program.

You might also like