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);
    }
}

How Java Package is useful

As we know each component of Java has special feathers. Among all Package is one of them, which is a collection of classes and interfaces grouped together as a logic unit.

There are some special feathers that a package holds. Such as:

Abstraction:
While developing large Java software we will arrange classes in a logical in a package. This can be achieved using Package. Actually we group the bunch of classes and interfaces together in a package but we behave it as a unit. For example we have imported java.util, java.awt etc many times.

Protection:
The use of package in java allows choosing which classes may be used outside the package and which one can’t. We may also give the class protection to be access and method protection to be overridden.

There are four level of protection :

  1. Public
  2. Default (friendly)
  3. Protected
  4. Private

This can be represented in package as shown in table:

Access is available to:

public

protected

default

private

All Classes

X

     

All Subclasses

X

X

   

Classes in the Same Package

X

X

X

 

The Class Itself

X

X

X

X

Convenience:
Convenience to work on team, using package programmers doesn’t need to bother about arranging and giving the name.

Name Space Control:
Two classes can have same name if they are in different package, which make programmers to not to concerned about using name already used in other package.