Package
A folder that is linked with java class is called package. It is used to group
related classes ,interfaces and enums. Also it is used to separate new
classes from existing classes. So by using package we can create multiple
classes with the same name, also we can create user defined classes with
predefined class names.
Packages are used in Java, in-order to avoid name conflicts and to control
access of class, interface and enumeration etc. A package can be defined as
a group of similar types of classes, interface, enumeration or sub-package.
Using package it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other
files.
Advantages of Packages:-
1) Clear Separation of classes and interfaces.
2) Easy to find,read and modify source code.
3) We can stop other programmers accessing our classes and its
members(security).
4) We can also solve name conflicts.
5) Project becomes easy to maintain.
Types of Packages in Java
There are two types of packages in java:
1. Java API packages or built-in packages and
2. User-defined packages.
Java API packages or built-in packages
Java provides a large number of classes grouped into different packages based
on a particular functionality.
2)User defined package:-
As the name suggests, these packages are defined by the user. We create a
directory whose name should be the same as the name of the package. Then
we create a class inside the directory.
Steps for Creating user-defined package:-
Step1: Simply include the package statement that must be the first
statement in java source file. Any class declare with in that file belongs to
that specified package.
Syntax:- package packagename;
Example:- package mypack;
Step2:- Next define the class that is to be put in the package and declare
that class as public.
Step3: Now save the file the with name given to class and add .java
extension.
Step4:-File is to be compiled as follows.
Sample.java
package mypack;
public class Sample
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Compilation:-
The java compiler doesn‟t create package physically in current working
directory just with javac command. package classes must be compiled with
„-d „ option to create package.
Syntax :-javac –d <path> filename
Here path specifies in which path package should be created.
Here –d functionality is creating package(folder) with the name mentioned in
the java file and moving all the .class files into that package and finally
storing the package in the given path
1)Example:- D:\ABN\javac –d . Sample.java
With this command compiler creates package(folder) “mypack” with
Example.class it in current working directory i.e D:\ABN directory.
Here .dot represents current working directory.
Execution :- D:\ABN\java mypack.Sample
2) Example:- D:\ABN\ javac –d C:\test Sample.java
With this command compiler creates package with “mypack” in c:\test
folder.
Rule:-test folder must be existed in C:\ drive before this program
compilation, else it leads to compilation error.
Execution:-
Here current package in C:\test folder ,now to execute this program we need
to set class path.
The CLASSPATH refers to the path on your file system where your .class
files are saved, and the classpath is defined by the CLASSPATH
environment variable.
The CLASSPATH environment variable specifies the directories where you
want the compiler and the JVM to search for bytecode
D:\ABN\ set classpath=c:\test;
D:\ABN\ java mypack.Sample
How to access package from another package:
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello java");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello java
2) Using packagename.classname:
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello
3) Using fully qualified name:
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output: Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you need
to import the subpackage as well.
Subpackage in java:
Package inside the package is called the subpackage. It should be created to
categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These
classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc and
so on. So, Sun has subcategorized the java package into subpackages such as lang,
net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output: Hello subpackage
How to send the class file to another directory or drive:
There is a scenario, I want to put the class file of A.java source file in classes folder
of c: drive.
For example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output: Welcome to package
}
While using packages and inheritance in a program, we should be aware of the visibility
restrictions imposed by various access modifiers.
Access protection
Access Modifier Public Protected Friendly Private private
protected
Access Location
Same class yes yes yes yes yes
Subclass in same package yes yes yes yes no
Other classes in same package yes yes yes no no
Subclass in other packages yes yes no yes no
Non-subclasses in other packages yes no no no No
Adding a class to a package
It is simple to add a class to an existing package. Consider the following package.
package p1;
public class A
// body of A
The package p1 contains one public class by name A. Suppose we want to add another class B to
this package. This can be done as follows:
1. Define the class and make it public
2. Place the package statement
package p1;
before the class definition as follows:
package p1;
public class B
package p1;
{ public class B{
//body op B
3. Store this as B.java under the directory p1
4. Compile B.java file. This will create a B.class file and place it in the directory p1.
Now, the package p1 will contain both the classes A and B.
A statement like import p1.*; will import both of them.
If we want to create a package with multiple public classes in it, we may follow the following
steps:
1. Decide the name of the package
2. Create a subdirectory with this name under the directory where main source files are stored.
3. Create classes that are to be placed in the package in separate source files and declare the
package statement
package packagename;
4. Switch to the subdirectory created earlier and compile each source file. When completed,
the package would contain .class files of all the source files.
Since a Java source file can have only one declared as public, we cannot put two or more public
classes together in a .java file.
This is because of the restriction that the file name should be same as the name of the public
class with .java extension.
Hiding Classes
When we import a package using asterisk ( * ), all public classes are imported. However, we
may prefer to “not import” certain classes.
That is, we may like to hide these classes from accessing from outside of the package. Such
classes should be declared “not public”.
Example
package p1;
public class X // public class available outside
//body of x
}
class Y
//body of y //not public, hidden
}
Here, the class Y which is not declared public is hidden from outside of the package p1.
This class can be seen and used by other classes in the same package.
Now, consider the following code, which imports the package p1 that contains class X and Y:
Import p1.*;
X objectx; //OK;class x is available here
Y objectY; //Not OK; y is not available
Static import
As import statement allows to use a class without its package qualification, static import
allows to access the static members of a class without class qualifications. For Example, to
access the static methods you need to call the using class name −
Math.sqrt(169);
But, using static import you can access the static methods directly.
Example
importstaticjava.lang.Math.*;
publicclassSample{
publicstaticvoidmain(String args[]){
System.out.println(sqrt(169));
Static import in Java allows to import static members of class and use them, as they are
declared in the same class. Static import is introduced in Java 5 along with other features
like Generics, Enum, Autoboxing and Unboxing and variable argument methods.
In order to access static members, it is necessary to qualify references with the class they came from.
For example, one must say:
double r = Math.cos(Math.PI * theta);