Package as a Custom tool library

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 https://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);
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: