Creating Custom-Defined Packages
Java is a friendly
language and permits to create our own packages and use in programming. We know
earlier, Java allows us to create our exceptions. Creating packages are
indispensable in project development where number of developers are involved
doing different modules and tasks. We know packages avoid name
collision problems. Package naming conventions are very helpful to
locate the applications developed by a single individual or team.
Following steps are to be followed in
creating and using packages.
- Create a package with a .class file
- set the classpath from the directory from which
you would like to access. It may be in a different drive and directory.
Let us call it as a target directory.
- Write a program and use the file from the
package.
First Step: Create a package add and place Addtion.class in it
Let us assume C:\java\jfiles is the current directory where we
would like to create the package.
C:\ java\jfiles > notepad Tiger.java
package add;
public class Addition{
public static void main(String
[]args){
int sum;
sum =
Integer.parseInt(args[0])+Integer.parseInt(args[1]);
System.out.println("\nSum
is:"+sum);
}
}
package is a keyword of Java followed by the package name. Just writing
the package statement followed by the name creates a new package.
The package statement must be first one in the program. If
exists, the import statement must be the second one. Our class declaration is
the third. Any order changes, it is a compilation error.
When the code is ready, the next job is compilation. We must
compile with package notation. Package notation uses –d compiler option as
follows-
C:\ java\jfiles > javac -d . Addition.java
The –d compiler option creates
a new folder called “add” and places the Addition.class in it. The dot (.) is
an operating system's environment variable that indicates the current
directory. It is an instruction to the OS to create a directory called forest
and place the Addition.class in it.
Second
step: Set the classpath from the target
directory.
Let us assume D:\java_programs is the
target directory. Let us access Tiger.class in forest package from here.
From the target directory set the
classpath following way.
D:\ java_programs >
set classpath=C:\ java\jfiles;%classpath%;
classpath is another environment variable which gives the
address of the “add” directory to the OS. %classpath% informs
the OS to append the already existing classpath to the current classpath that
is right now set.
Third Step: Now finally, write a program or run the above program using
the following java command.
C:\java\jfiles>java
add.Addition 5 10
Output Shows :
Sum is: 15