9 Packages
9 Packages
Chapter 9&10
Packages 2
Packages are containers for classes that are used to keep the class name space
compartmentalized.
They also help in avoiding naming conflicts between classes and interfaces
with the same name but defined in different packages.
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.
Each package in Java has its unique name and organizes its
classes and interfaces into a separate namespace, or name group
4
Any classes declared within that file will belong to the specified
package.
If you omit the package statement, the class names are put into the
default package, which has no name.
7
Contd..
• This is the general form of the package statement:
Demo.java
package MyPackage;
Java uses file system directories to store
packages class exp{
}
class Demo{
public static void main(String args[]){
…
}
}
8
Contd..
Java uses file system directories to store packages
Demo.java
package MyPackage;
class exp{
} Try.java
package MyPackage;
class Demo{
public static void main(String args[]){ class xyz{
… }
}
} class Try{
public static void main(String a
…
}
}
9
Contd..
• 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]];
class Balance
class AccountBalance {
{ public static void main(String args[])
String name;
double bal;
{
Balance(String n, double b) Balance current[] = new Balance[3];
current[0] = new Balance("Fielding", 12.23);
{ current[1] = new Balance("Will", 157.02);
name = n; current[2] = new Balance("Tom ", -12.33);
bal = b; for(int i=0; i<3; i++)
}
void show() current[i].show();
}
{ }
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" +
bal);
}
}
14
Class Member
Access
18
}
19
}
20
}
To test file for package p1
package p2;
24
Importing Packages
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.
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.
In a Java source file, import statements occur immediately
following the package statement (if it exists) and before any class
definitions.
Importing Packages
• the import statement is optional.
• Any place you use a class name, you can use its
fully qualified name, which includes its full package
hierarchy.
• example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date {
}