Just like system packages, the users of java language can also create their own packages. They are called user defined packages.
To create a user defined package we use the keyword "package" and the following are steps for creating your own package in java.
1. Declare the classes that are to put in the package and declare it as public.
2. Now compile the programe as ( if your program is named as MyMath.java)
javac -d . MyMath.java
First we create a class and then include this class in package called " arithmetic"
package arithemetic; public class MyMath { public int add(int x, int y) { return(x+y); } public int sub(int x, int y) { return(x-y); } public int mul(int x, int y) { return(x*y); } public int div(int x, int y) { return(x/y); } public int mod(int x, int y) { return(x%y); } }
On successful compilation of the program you will see a folder (directory) name as arithmetic and it contains MyMath.class file
Accessing a package
Like system packages the user defined packages can also be used in your java program.
If you want to access a class contained in a user defined package, the following program help you
import arithemetic.MyMath; class use { public static void main(String args[]) { MyMath m = new MyMath(); System.out.println(m.add(8,5)); System.out.println(m.sub(8,5)); System.out.println(m.mul(8,5)); System.out.println(m.div(8,5)); System.out.println(m.mod(8,5)); } }
The output of the above program is
D:\java examples>javac use.java
D:\java examples>java use
13
3
40
1
3
How to add an interface or class to existing package?
To add an interface or class to existing package first create program and generate dot class file to it and them store this dot class file in the package directory
To add a class called "message" to the above package "arithemetic", first create the dot class file and them we place it in the package. This can be done in a single step at the compilation stage as
package arithemetic; public class message { public void msg() { System.out.println("Hi! I am new class added to package"); } }
javac -d . message.java
The preceding command means create a package(-d) in the current directory(.) and store message.class file there in the package
Now I am accessing the classes of the package as
import arithemetic.MyMath; import arithemetic.message; class use { public static void main(String args[]) { MyMath m = new MyMath(); System.out.println(m.add(8,5)); System.out.println(m.sub(8,5)); System.out.println(m.mul(8,5)); System.out.println(m.div(8,5)); System.out.println(m.mod(8,5)); message m1=new message(); m1.msg(); } }
and it will generate output as
D:\java examples>javac -d . message.java
D:\java examples>javac use.java
D:\java examples>java use
13
3
40
1
3
Hi! I am new class added to package
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.