A Package Is A Collection of Similar Types of Classes
A Package Is A Collection of Similar Types of Classes
Purpose of package
The purpose of package concept is to provide common classes and interfaces for any program separately. In
other words if we want to develop any class or interface which is common for most of the java programs than
Packages in Java are the way to organize files when a project has many modules. Same like we organized our
files in Computer. For example we store all movies in one folder and songs in other folder, here also we store
same type of files in a particular package for example in awt package have all classes and interfaces for design
GUI components.
Advantage of package
Package is used to categorize the classes and interfaces so that they can be easily maintained
Type of package
Package are classified into two type which are given below.
If any package is design by the user is known as user defined package. User defined package are those which
are developed by java programmer and supply as a part of their project to deal with common requirement.
Choose an appropriate class name or interface name and whose modifier must be public.
Any package program can contain only one public class or only one public interface but it can contain
Package program should not contain any main class (that means it should not contain any main())
modifier of constructor of the class which is present in the package must be public. (This is not
The modifier of method of class or interface which is present in the package must be public (This rule
Every package program should be save either with public class name or public Interface name
Compile package programs
For compilation of package program first we save program with public className.java and it compile using
below syntax:
Syntax
javac -d . className.java
Syntax
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for
the given package in given path. When we give specific path then it create a new folder at that location and
Package program which is save with A.java and compile by javac -d . A.java
Example
package mypack;
public class A
System.out.println("Sum method");
Example
import mypack.A;
A a=new A();
a.show();
Explanations: In the above program first we create Package program which is save with A.java and compiled
by "javac -d . A.java". Again we import class "A" in class Hello using "import mypack.A;" statement.