0% found this document useful (0 votes)
54 views20 pages

Packages

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)
54 views20 pages

Packages

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/ 20

Outline

1 Introduction to Packages

2 Access Protection

3 Importing Packages
Packages
A package (act as Container) is a collection of related java entities (such as classes, interfaces
exceptions, errors and enums), a great way to achieve reusability, can be considered as means to
achieve data encapsulation.
Packages in Java provides a mechanism for partitioning the class name space into more manageable
chunks.
The Package is both a naming and a visibility control mechanism

The advantages of packages are:

Removes naming collision: by prefixing the class name with a package name.
Provides access control: Besides public and private, Java has two access control modifiers-
protected and default (that are related to package).
Provides easy maintenance:
Categorize the classes and interfaces so that they can be easily maintained.

Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
Packages
Package in java can be categorized in two form, built-in package and user-defined
package.

Built-in packages: standard packages which are part of JRE or Java API. Some of the
commonly used built-in packages are:
Defining a Package
To create a package is quite easy: simply include a package statement as the first
statement in a Java source file.
Any classes declared within that file will belong to the specified package.

package statement defines a name space in which classes are stored.

If the package statement is omitted, the class names are put into the default package,
which has no name, and suitable for short, sample programs but inadequate for real
applications.

Most of the time, for real applications, you will define a package for the code, using the
general form:
package pkgname; // for example, package MyPackage;
Defining a Package
package MyPackage; // creates a package called MyPackage;
1 Java uses file system directories to store packages.

2 For example, the .class files for any classes will be declared as a part of MyPackage and
must be stored in a directory called MyPackage. Remember that case is significant, and
the directory name must match the package name exactly.

3 More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not exclude
other classes in other files from being part of that same package. Most real-world
packages will spread across many files.

4 It is possible to create a hierarchy of packages. To do so, simply separate each package


name from the one above it by use of a period. The general form is:
package pkg1[.pkg2[.pkg3] ];
Defining a Package
package MyPackage; // creates a package called MyPackage;
5 A package hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as:
package java.awt.image; //needs to be stored in java/awt/image in a UNIX
environment.
6 Be sure to choose package names carefully. It is not possible to rename a package without
renaming the directory in which the classes are stored.
Package Example
1 How to compile Java Package program Syntax:
// A simple package javac -d directory javafilename
package MyPack;
class Balance { 2 Example: javac -d . AccountBalance.java
String name; //creates package MyPack in current directory (.)
double bal; and saves the generated .class files( Balance.class
Balance(String n, double b) { and AccountBalance.class) in it. This step can be
name = n; performed manually as well.
bal = b;}
3 How to run Java Package program.
void show( ) {
if(bal < 0 )
java MyPack.AccountBalance
System.out.print("--> ");
System.out.println(name + ": $" + bal);
This program displays the following output :
}}
class AccountBalance { K. J. Fielding: $123.23
public static void main(String args[ ]) { Will Tell: $157.02
Balance current[ ] = new Balance[3]; --> Tom Jackson: $-12.33
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33); * 3 ways are there to locate/run Java Packages
for(int i=0; i<3; i++) { current[i].show( ); } program (other two are discussed in next slide)
Finding Packages and CLASSPATH
How does the Java run-time system know where to look for the created packages ?

1 By default, the Java run-time system uses the current working directory as its starting point. Thus,
if the package is in a subdirectory of the current directory, it will be found there.
Already Discussed in previous slide

2 It is possible to specify a directory path or paths by setting the CLASSPATH environmental


variable. (in Unix/Linux systems)
export CLASSPATH=.:/home/UserName/Desktop/MyJavaPrograms;
// Assuming the packages are saved under Desktop/MyJavaPrograms;

3 It is possible to use the -classpath option with java and javac to specify the path to your classes.
java -classpath /home/UserName/Desktop/MyJavaPrograms/ MyPack.AccountBalance

// Assuming packages are saved under Desktop/MyJavaPrograms;


// Save all .class files of your program(AccountBalance.java) in MyPack.
Access Protection
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:
1 Non-subclasses in the same package
2 Subclasses in the same package
3 Subclasses in different package
4 Classes that are neither in the same package nor subclasses
Access Protection
The three access modifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.

The following applies only to members of classes

[ Source: (1) ]
Access Protection
Anything declared public can be accessed from anywhere.

Anything declared private cannot be seen outside of its class.

When a memberdoes not have an explicit access specification, it


is visible to subclasses as well as to other classes in the same package (default
access).

To allow an element to be seen outside the current package, but only to classes that
are subclasses of the class directly, then declare the element as protected.
Access Protection
A non-nested class has only two possible access
levels default and public (others are abstract
and final)

When a class is declared as public, it is accessible by any other code.

If a class has default access, then it can only be accessed by other code within its
same package.

When a class is public, it must be the only public class declared in the file, and the
file must have the same name as the class
An Access Example
// Shows all combinations of the access control modifiers.
// This example has two packages and five classes. This is file Derived.java:

This is file Protection.java: package p1;


package p1; class Derived extends Protection {
public class Protection
{ Derived( ) {
int n = 1;
private int n_pri = 2; System.out.println("derived constructor");
protected int n_pro = 3; System.out.println("n = " + n);
public int n_pub = 4;
public Protection( ) // private member in Protection class
{ System.out.println("base constructor"); // System.out.println("n_pri = "+ n_pri);
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro);
System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub);
System.out.println("n_pub = " + n_pub); }
} }
}
An Access Example
This is file SamePackage.java: This is test file for package P1, DemoP1.java:
package p1;
// Demo package p1
class SamePackage {

SamePackage(){ package p1;

Protection p = new Protection( );


System.out.println("same package constructor"); // Instantiate the various classes in p1.
public class DemoP1 {
System.out.println("n = " + p.n); public static void main(String args[ ]) {
Protection ob1 = new Protection( ); Derived
// class only
// System.out.println("n_pri = " + p.n_pri); ob2 = new Derived( ); SamePackage ob3 = new
System.out.println("n_pro = " + p.n_pro);
SamePackage( );
System.out.println("n_pub = " + p.n_pub);
}
}} }
An Access Example
How to compile? This program displays the following output :
base constructor n = 1
1 Compile all one by one in
n_pri = 2
classes sequence: n_pro = 3
$ javac -d . Protection.java n_pub = 4
base constructor n =1
$ javac -d . Derived.java n_pri = 2
$ javac -d . SamePackage.java n_pro = 3
$ javac -d . DemoP1.java n_pub = 4
derived constructor n = 1
n_pro = 3
OR n_pub = 4
base constructor n = 1
2 Compile all classes all together but in n_pri = 2
sequence n_pro = 3
n_pub = 4
$ javac -d . Protection.java Derived.java same package constructor n = 1
SamePackage.java DemoP1.java n_pro = 3
n_pub = 4
How to run?
R $ java p1.DemoP1
An Access Example
This is file OtherPackage.java:
This is file Protection2.java:
package p2;
package p2; class OtherPackage {
class Protection2 extends p1.Protection
OtherPackage( ) {
{ Protection2( ) {
p1.Protection p = new p1.Protection( );
System.out.println("derived other System.out.println("other package constructor");
package constructor");
// class or package only
// class or package only // System.out.println("n = " + p.n);
// System.out.println("n = " + n);
// class only
// class only // System.out.println("n_pri = " + p.n_pri);
// System.out.println("n_pri = " + n_pri);
// class, subclass or package only
System.out.println("n_pro = " + n_pro); // System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " +
n_pub); System.out.println("n_pub = " + p.n_pub);
} }
} }
An Access Example
This program displays the following output :
This is test file for package P2, DemoP2.java:
// Demo package p2. base constructor
n=1
package p2; n_pri = 2
n_pro = 3
n_pub = 4
// Instantiate the various classes in p2 derived other package
public class DemoP2 { constructor n_pro = 3
public static void main(String args[ ]) { n_pub = 4
Protection2 ob1 = new Protection2( ); base constructor
n=1
OtherPackage ob2 = new OtherPackage( ); n_pri = 2
n_pro = 3
n_pub = 4
}
other package
}
constructor n_pub = 4
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. (Since classes within
packages must be fully qualified with their package name or names, it could become tedious to
type in the long dot-separated package path name for every class you want to use.)
The import statement saves a lot of typing. (If you are going to refer to a few dozen classes in
your application)
In a Java source file, import statements occur immediately following the packagestatement
(if it exists) and before any class definitions.

The general form of the import statement: 1 Here pkg1 is the top-level package, and pkg2 is
import pkg1[.pkg2].(classname|*); the subordinate package inside the outer
package separated by a dot (.).
For example:
import //Explicit Date class 2 There is no practical limit on the depth of a
//Entire io package package hierarchy, except that imposed by the
java.util.Date;
file system.
import java.io.*;
Importing Packages
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 (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.*;
The import statement is optional. The user should use a class name with its its fully qualified
name, which includes its full package hierarchy.
For example:
import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date { // fully-qualified name
Importing Packages
/* when a package is imported, only those items within the /* Here TestBalance imports MyPack and is then able to make use of
package declared as public will be available to non- the Balance class: */
subclasses in the importing code. */ import MyPack.Balance;

package MyPack; //import MyPack.*;

/* Now, the Balance class, its constructor, and its show( )


method are public. This means that they can be used by non- class TestBalance {
subclass code outside their package */
public static void main(String args[ ]) {
public class Balance {
/* Because Balance is public, you may use Balance
String name;
class and call its constructor. */
double bal;
Balance test = new Balance("J. J. Jaspers", 99.88); test.show(
public Balance(String n, double b) {
name = n;
);
bal = b;
} A Remove the public specifier from
public void show( ) { Balance
}
class the and then try compiling
if( bal < 0 ) }
TestBalance.
System.out.print("--> ");
System.out.println(name + ": $" + bal);

You might also like