0% found this document useful (0 votes)
0 views9 pages

Java Packages

A Java package is a collection of related classes and interfaces, categorized into built-in and user-defined packages. Packages provide advantages such as organization, access protection, and avoidance of naming collisions. The document explains how to define, compile, run, and import packages, as well as access control mechanisms and the concept of subpackages.

Uploaded by

mondalrathin25xy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views9 pages

Java Packages

A Java package is a collection of related classes and interfaces, categorized into built-in and user-defined packages. Packages provide advantages such as organization, access protection, and avoidance of naming collisions. The document explains how to define, compile, run, and import packages, as well as access control mechanisms and the concept of subpackages.

Uploaded by

mondalrathin25xy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be
categorized in two form, built-in package and user-defined package. There are many built-in packages such
as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed learning of creating and
using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a Java source
file. Any classes declared within that file will belong to the specified package. The package statement
defines a name space in which classes are stored. If you omit the package statement, the class names are put
into the default package, which has no name. (This is why you haven’t had to worry about packages before
now.) While the default package is fine for short, sample programs, it is inadequate for real applications.
Most of the time, you will define a package for your code.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.

package MyPackage;

Java uses file system directories to store packages. For example, the .class files for any classes you declare
to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is
significant, and the directory name must match the package name exactly.

Simple example of java package


The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name
like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the
same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
import package.*;
import package.classname;
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");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello

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.
Note: Sequence of the program must be package then import then class.

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 defined 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.
The standard of defining package is domain.company.package.

Example of Subpackage
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

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.
 Temporary
 By setting the classpath in the command prompt
 By -classpath switch
 Permanent
 By setting the classpath in the environment variables
 By creating the jar file, that contains all the class files, and copying the jar file in the
jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
//save as C.java otherwise Compilte Time Error

class A{}
class B{}
public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public class,
but keep the package name same. For example:
//save as A.java
package Pkg1;
public class A{}
//save as B.java
package Pkg2;
public class B{}
Access Protection
In the preceding chapters, you learned about various aspects of Java’s access control mechanism and its
access specifiers. For example, you already know that access to a private member of a class is granted only
to other members of that class. Packages add another dimension to access control. As you will see, Java
provides many levels of protection to allow fine-grained control over the visibility of variables and methods
within classes, subclasses, and packages. Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods. Packages act as containers for classes and
other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest unit of
abstraction. Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Classes that are neither in the same package nor subclasses

The three access specifies, private, public, and protected, provide a variety of ways to produce the many
levels of access required by these categories.

While Java’s access control mechanism may seem complicated, we can simplify it as follows. Anything
declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its
class. When a member does not have an explicit access specification, it is visible to subclasses as well as to
other classes in the same package. This is the default access. If you want to allow an element to be seen
outside your current package, but only to classes that subclass your class directly, then declare that element
protected.

An Access Example
The following example shows all combinations of the access control modifiers. This example has two
packages and five classes. Remember that the classes for the two different packages need to be stored in
directories named after their respective packages—in this case, p1 and p2.

The source for the first package defines three classes: Protection, Derived, and SamePackage. The first
class defines four int variables in each of the legal protection modes. The variable n is declared with the
default protection, n_pri is private, n_pro is protected, and n_pub is public.

Each subsequent class in this example will try to access the variables in an instance of this class. The lines
that will not compile due to access restrictions are commented out by use of the single-line comment //.
Before each of these lines is a comment listing the places from which this level of protection would allow
access.
The second class, Derived, is a subclass of Protection in the same package, p1. This grants Derived access
to every variable in Protection except for n_pri, the private one. The third class, SamePackage, is not a
subclass of Protection, but is in the same package and also has access to all but n_pri.
This is file Protection.java:
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

This is file Derived.java:


package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file SamePackage.java:
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

Following is the source code for the other package, p2. The two classes defined in p2 cover the other two
conditions which are affected by access control. The first class, Protection2, is a subclass of p1.Protection.
This grants access to all of p1.Protection’s variables except for n_pri (because it is private) and n, the
variable declared with the default protection. Remember, the default only allows access from within the
class or the package, not extra-package subclasses. Finally, the class OtherPackage has access to only one
variable, n_pub, which was declared public.

This is file Protection2.java:


package p2;
class Protection2 extends p1.Protection
{
Protection2()
{
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

This is file OtherPackage.java:


package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
If you wish to try these two packages, here are two test files you can use. The one for package p1 is shown
here:
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
The test file for p2 is shown next:
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}

Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into visibility. Once
imported, a class can be referred to directly, using only its name. The import statement is a convenience to
the programmer and is not technically needed to write a complete Java program. If you are going to refer to
a few dozen classes in your application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package statement (if it exists) and
before any class definitions. This is the general form of the import statement:

import pkg1[.pkg2].(classname|*); LANGUAGE


Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the
outer package separated by a dot (.). There is no practical limit on the depth of a package hierarchy, except
that imposed by the file system. Finally, you specify either an explicit classname or a star (*), which
indicates that the Java compiler should import the entire package. This code fragment shows both forms in
use:

import java.util.Date;
import java.io.*;
The star form may increase compilation time—especially if you import several large packages. For this
reason it is a good idea to explicitly name the classes that you want to use rather than importing whole
packages. However, the star form has absolutely no effect on the run-time performance or size of your
classes.

All of the standard Java classes included with Java are stored in a package called java. The basic language
functions are stored in a package inside of the java package called java.lang. Normally, you have to import
every package or class that you want to use, but since Java is useless without much of the functionality in
java.lang, it is implicitly imported by the compiler for all programs. This is equivalent to the following line
being at the top of all of your programs:

import java.lang.*;
If a class with the same name exists in two different packages that you import using the star form, the
compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-
time error and have to explicitly name the class specifying its package.
Any place you use a class name, you can use its fully qualified name, which includes its full package
hierarchy. For example, this fragment uses an import statement:

import java.util.*;
class MyDate extends Date
{
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date
{
}
If you want the Balance class of the package MyPack shown earlier to be available as a stand-alone class
for general use outside of MyPack, then you will need to declare it as public and put it into its own file, as
shown here:

package MyPack;
/* Now, the Balance class, its constructor, and its show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}

As you can see, the Balance class is now public. Also, its constructor and its show( ) method are public,
too. This means that they can be accessed by any type of code outside the MyPack package. For example,
here TestBalance imports MyPack and is then able to make use of the Balance class:
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
/* Because Balance is public, you may use Balance class and
call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then try compiling TestBalance.
As explained, errors will result.

Importing a Package Member


import graphics.Rectangle;

Importing an Entire Package


import graphics.*;

The Static Import Statement


There are situations where you need frequent access to static final fields (constants) and static methods from
one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static
import statement gives you a way to import the constants and static methods that you want to use so that you
do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, including methods for calculating
sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,
public static final double PI 3.141592653589793
public static double cos(double a)
Ordinarily, to use these objects from another class, you prefix the class name, as follows.
double r = Math.cos(Math.PI * theta);

You can use the static import statement to import the static members of java.lang.Math so that you don't
need to prefix the class name, Math. The static members of Math can be imported either individually:
import static java.lang.Math.PI;
or as a group:
import static java.lang.Math.*;

Once they have been imported, the static members can be used without qualification. For example, the
previous code snippet would become:
double r = cos(PI * theta);

Obviously, you can write your own classes that contain constants and static methods that you use frequently,
and then use the static import statement. For example,
import static mypackage.MyConstants.*;

Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read and
maintain, because readers of the code won't know which class defines a particular static object. Used
properly, static import makes code more readable by removing class name repetition.

You might also like