Package as a Custom tool library
February 24, 2009 Leave a comment
We can use Package concept to create our own libraries of tools to reduce or eliminate duplication of the code. Here we have a Package example where System.out.println and System.out.printf has been replaced with alias print and printf.
package learnjava;
import java.io.*;
//Print.java
public class Print
{
public static void print(Object obj)
{
System.out.println(obj);
}
public static void print()
{
System.out.println(“”);
}
public static void printnb(Object obj)
{
System.out.print(obj);
}
//For printf() method we may refer http://www.java2s.com/
//And for argument “Object… obj” go through my previous post http://wowjava.wordpress.com/
public static PrintStream
printf(String format, Object… obj)
{
return System.out.printf(format, obj);
}
}
Now in below example, we have imported all the static methods of above java file Print.java. Then we are using the methods and appropriate argument for those methods.
//Only uses those methods which are Static
import static learnjava.Print.*;
//PrintTest.java
class PrintTest
{
public static void main(String[] args) {
print(“This is just a test.”);
int a=30;
print(“Displaying variable “+ a);
printf(“%s”,”Output is “);
printf(“%f”,21.342);
}
}

Recent Comments