Please wait ......

Need For Packages

Learn why packages are needed.


Assume there are two students in a class with same name "Pradeep". We need some criteria to distinguish between the two Pradeep.

The criteria can be

  1. Size (we can say Fat Pradeep and Lean Pradeep)
  2. Height (we can say Tall Pradeep and short Pradeep)
  3. Their school/college registration number (which is guaranteed to be unique for each Pradeep)

Hence packages allow Java to distinguish between two or more classes having same name. The classes will have same name but must reside in different packages.

Let us now create 2 Java classes with same name "NationalityPrinter.java" but in different packages.

package com.skillrack.examples.indian;

public class NationalityPrinter {
    public static void printNationality(){
        System.out.println("Indian");
    }
}

Note that the second Java class given below is in a different package com.skillrack.examples.russian

package com.skillrack.examples.russian;

public class NationalityPrinter {
     public static void printNationality(){
        System.out.println("Russian");
    }
}

Now in any other Java program, we can refer to the desired NationalityPrinter class by importing the class using the package. For example the below Java program imports NationalityPrinter class under com.skillrack.examples.russian and hence will print "Russian"