You are on page 1of 26

PACKAGES

A package in Java is a collection of classes and interfaces.

Importance:

 Packages are used to keep class name space compartmentalized.


 For example, a package allows you to create a class named List, which you
can store in your own package without concern that it will collide with some
other class named List stored elsewhere. This means that a unique name had
to be used for each class to avoid name collisions.

What are packages?

 Java provides a mechanism for partitioning the class name space into
more manageable chunks. This mechanism is the package.
 The package is both a naming and a visibility control mechanism.
 You can define classes inside a package that are not accessible by code
outside that package.
 You can also define class members that are only exposed to other members
of the same package.
 This allows your classes to have intimate knowledge of each other, but not
expose that knowledge to the rest of the world

Defining a Package

 To create package add package statement in the first line of java source
file. Hence any classes declared within that file will belong to that 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 the general form of the package statement:
package pkg;

For example, the following statement creates a package called MyPackage.


package MyPackage;

 You can 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 of a multileveled package statement is shown here:

package pkg1[.pkg2[.pkg3]];

 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;

Remember:

1. package declaration should be the first line in you Java file.

2. You can have only one package declaration in one Java file.
Finding Packages and CLASSPATH

How does the Java run-time system know where to look for packages that you
create?

The answer has two parts.

First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in the current directory, or a subdirectory of
the current directory (in case of package statement in source program), it will be
found.

Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.

Third from classpath variable set from command prompt.

For example, consider the following package specification.

package MyPack;

In order for a program to find MyPack, one of two things must be true. Either the
program is executed from a directory immediately above MyPack, or
CLASSPATH must be set to include the path to MyPack. (if no package
statement in source program) and to before MyPack (when package statement is
included in source program)

Importing Packages
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|*);

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.*;

Remember:

import must come after package declaration.

One class can have multiple import statement.

Example:

Balance.java

package p1;

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);


}
}
Test.java
import p1.*;

class Test
{
public static void main(String args[])
{

Balance test = new Balance("abc",100);


test.show();
}
}

Way 1

Way 2
static import

The static import feature of Java 5 facilitates the java programmer to access any
static member of a class directly. There is no need to qualify it by the class name.

Advantage of static import:

 Less coding is required if you have access any static member of a class
often.

Disadvantage of static import:

 If you overuse the static import feature, it makes the program unreadable and
un maintainable.

Simple Example of static import

import static java.lang.System.*;

class StaticImportExample
{
public static void main(String args[])
{
out.println("Hello");//Now no need of System.out
out.println("Java");

}
}

What is the difference between import and static import?

The import allows the java programmer to access classes of a package without
package qualification whereas the static import feature allows accessing the static
members of a class without the class qualification. The import provides
accessibility to classes and interface whereas static import provides accessibility to
static members of the class.

Finally few points worth remembering about static import in Java :

1) Static import statements are written as "import static" in code and not "static
import".

2) If you import two static fields with same name explicitly e.g.
Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile
time error. But if other static modifier is not imported explicitly e.g. you have
imported java.lang.Long.*, MAX_VALUE will refer to Integer.MAX_VALUE.

3) Static import doesn't improve readability as expected, as many Java


programmers prefer Integer.MAX_VALUE which is clear that which
MAX_VALUE you are referring.

4) You can apply static import statement not only on static fields but also on static
methods in Java.
Access Control mechanism/ access modifiers / visibility control
mechanism in java

 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
 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.

Remember

Table 9-1 applies only to members of classes – variables and methods

For classes in java

 A class has only two possible access levels: default and public.
 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.
An Access Example
Description
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.
Hierarchy of file system
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);
}
}

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);
}
}
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);
}
}

Demo.java
package p1;

public class Demo


{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
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);
}
}

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);
}
}
Demo2.java
package p2;

public class Demo2


{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Compilation
Here remember classpath is required for p1 packages classes because they are
using Protection.class file whenever they make its object or use as ‘extends
Protection’. otherwise in same packages when we are dealing with classpath is
never required.

Executing
since classpath has been already set.

Way1
Way2
Removing classpath since now not needed and moving to one up folder of what is mentioned in
the programs i.e. class
Access Modifiers classification as
1) Class modifiers

2) Variable Modifiers

3) Constructor Modifiers

4) Method Modifiers

1) Class Modifiers

Following can be used

Modifier Meaning

abstract Cannot be instantiated


final Cannot be extended
public can be accessed all over
default public Can be accessed by same package
static Only inner class can be static and can access only static
members.

 abstract class can have abstract as well as concrete methods and cannot be
instantiated.
 final class cannot be extended. If class is declared final then all the methods
are also declared final
 The abstract and final class are mutually exclusive.
 public class can be accessed by any application
 If none of these access specifiers are provided then class is assumed to be
neither abstract nor final and may be accessed only by the code in same
package
2) Variable Modifiers

Following are the modifiers

Modifier Meaning

public can be accessed anywhere


private can be accessed by the code in the same class
protected can be accessed by the code in same package and by the
code in subclass of the different package
default public can be accessed by the code in same package
final it is constant, value can’t be changed
static is not an instance variable but commonly shared by all
instances
transient Is not the part of persistent state of the class
volatile can change unexpectedly

public , private and protected access specifiers are mutually exclusive i.e. can’t be
used together.

3) Constructor Modifiers

Following are the modifiers

Modifier Meaning

public Can be invoked by code in the any class


private Can be invoked by code in the same class
protected Can be invoked by code in the any class in same
package and in the subclass of the different package
default public Can be invoked by code in the same package

These all modifiers are mutually exclusive.


4) Method Modifiers

Following are method modifiers

Modifier Meaning

public can be invoked by all classes


private can be invoked by the code in the same class
protected can be invoked by the code in same package and by the code
in subclass of the different package
default public can be invoked by the code in same package
final cannot be overridden
static is not an instance method but commonly shared by all
instances
synchronized Acquires lock when it begins execution
abstract Implementation is not provided
native The method is implemented in the machine code used by the
host CPU, not using JAVA bytecodes.

If a class contains an abstract method that class itself must be also is declared
abstract.

The public, private and protected access specifiers are mutually exclusive.

The synchronized is used in multithreaded programming.


Classroom Big Program

Hierarchy of the Program


A.java

package p1;
public class A
{
int a;
public A(int a)
{
this.a=a;
}
public void display()
{
System.out.println(a);
}
}

B.java
package p2;
public class B
{
int b;
public B(int b)
{
this.b=b;
}
public void display()
{
System.out.println(b);
}
}
C.java
package p1.p11;
public class C
{
int c;
public C(int c)
{
this.c=c;
}
public void display()
{
System.out.println(c);
}
}

all.java
package pfinal;

import p1.A;
import p2.B;
import p1.p11.C;

public class all


{
public static void main(String args[])
{
A a1 = new A(10);
a1.display();

B b1 = new B(20);
b1.display();

C c1 = new C(30);
c1.display();
}
}
Compiling

Now while compiling all.java requires classpath since it contains import statements
to packages p1,p2,p1.p11 which are not present in current directory i.e. src

Remember classpath requires to set for two things

i) when there is import statement

ii) while executing .class file from other place i.e. here from src folder.
Executing
Way1

From current directory, since class path had been already set

Way2

From the directory above the package mentioned in the programs

Here classpath settings are not required.

You might also like