Understanding Java Packages and APIs
Understanding Java Packages and APIs
Packages in Java - I
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Concept of Package in Java
Two unique features in Java
Packages Interfaces
What is a package?
A package is a container for the classes that are used to keep the
class name space compartmentalized
Example:
You can contain all classes related to all sorting programs in your own package.
Why packages?
It allows flexibility to give same name but to many classes, that is to avoid name
space collision.
The packages in Java provides mechanism for partitioning the class name space into
more manageable chunks.
In Java, already many predefined packages are available, those are to help programmers
to develop their software in an easy way.
Example:
[Link] is a package in Java providing all basic supports in developing GUI programs.
Packages in Java
• Code reusability is the main philosophy of Object-Oriented Programming.
• To power this advantage, Java has a number of packages called API bundled with the
JDK.
• Packages are collection of classes and interfaces to facilitate a number of ready made
solutions.
• A great knowledge of packages helps a Java developer to master in Java solution.
• In addition to the API, user can maintain their own packages.
API – The Built-in Java packages
API
Window ToolKit
Core Packages and Applet
Example:
[Link] toDay = new [Link] ( );
[Link](toDay);
The same thing but with import statement can be done as follows
import [Link];
Date today = new Date( );
Defining Packages in Java
User defined packages
• User can maintain their own package.
• Java uses file system directories to store packages.
• The package statement can be used for the purpose with the following syntax
package myPackage;
public Class myClass {
. . .
. . .
}
Here, myPackage is the name of the package and it contains the class myClass.
Package naming conventions
• Packages are usually defined using a hierarchical naming pattern, with levels
in the hierarchy separated by periods (.) .
• Although packages lower in the naming hierarchy are often referred to a "sub
packages" of the corresponding packages higher in the hierarchy, there is no
semantic relationship between packages.
Organizational package naming conventions
• Frequently, a package name begins with the top level domain name of the
organization and then the organization's domain and then any subdomains listed
in the reverse order.
• The organization can then choose a specific name for their package.
User defined packages
• Classes that are not reused together should not belong to the same package.
Package declaration
Package declaration is file based
• All classes in the same source file belong to the same package.
• Each source file may contain an optional package declaration in the following form.
package <PackageName>;
Let us consider the source file [Link], for example.
package elevator;
public class ElevatorFrame {
public double x;
//……..
}
Package declaration
• The package declaration at the top of the source file declares that the
ElevatorFrame class belongs to the package named elevator.
• When the package declaration is absent from a file, all the classes contained in the
file belong to unnamed package.
• A class in a named package can be referred in two ways.
User defined packages: Example
// User defined package in a subdirectory, say MyPackage
package MyPackage;
public class MyClass {
public void test ( ) {
[Link] ( " Welcome to My Class !");
}
}
/* Import the package with the following code. From another distant file/
program */
import [Link];
class PackageTestAppln {
public static void main ( String args [ ] ) {
MyClass theClass = new MyClass ( );
[Link] ( );
}
}
User defined packages: Example
Note:
We cannot put two or more public classes together in a .java file; otherwise there will be an
ambiguity in naming the .java file
package P; Steps
public class A { 1. Create a directory named P.
. . .
}
2. Store the class A in the file [Link] in it
3. Compile [Link] and place it in the
directory P.
package P;
public class B {
4. Store the class B in the file [Link] in it
. . . 5. Compile [Link] and place it in the
} directory P.
6. import P.*;
will import all classes in the package P.
Question to think…
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Accessing a Package
Finding packages and CLASSPATH
• Third, you can use the -classpath option with java and
javac to specify the path to your classes.
Finding packages and CLASSPATH: Example
Consider the following package specification:
package MyPack;
The program can be executed from a directory
For a program immediately above MyPack
to find
The CLASSPATH must be set to include the path to
MyPack, one MyPack
of three things
must be true. The -classpath option must specify the path to
MyPack when the program is run via java.
When the second two options are used, the class Example: In a Windows environment, if the path to
path must not include 𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀, itself. It must 𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀 is
simply specify the path to 𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀. C:\MyPrograms\Java\MyPack
then the class path to MyPack is
C:\MyPrograms\Java
Finding packages and CLASSPATH: Example
package MyPack;
class Balance {
String name;
class AccountBalance {
double bal;
public static void main(String args[]) {
Balance(String n, double b) {
Balance current[] = new Balance[3];
name = n;
current[0] = new Balance("K. J. Fielding", 123.23);
bal = b;
current[1] = new Balance("Will Tell", 157.02);
}
current[2] = new Balance("Tom Jackson", -12.33);
void show() {
for(int i=0; i<3; i++)
if(bal<0)
current[i].show();
[Link](“Account is dead");
}
else
}
[Link](name+": $ "+bal);
}
}
Finding packages and CLASSPATH: Example
Call this file Then, try executing the
[Link] and put AccountBalance class, using
it in a directory called the following command line:
MyPack. java [Link]
As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself.
That is, you cannot use this command line:
java AccountBalance
Importing a Package
Importing a package
This is the general form of the import statement:
import pkg1 [.pkg2].(<classname> | *);
Here, pkg1 is the name of a top-level package
pkg2 is the name of a sub-ordinate 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 class name or a star (*), which indicates that the Java compiler
should import the entire package.
Example:
import [Link];
import [Link].*;
Using package
Class in a named package can be referred to in two different ways
Import a class or all the classes in the designated package using
import PackageName.<ClassName>;
import Packagename.*;
Example
The ElevatorPanel class in package elevator can simply be referred to as elevator
when either of the following import clauses occurs at the top of source file
import [Link];
import elevator.*;
Access Protection for
Packages
Access protection
Because of the interplay between classes and packages, Java addresses four
categories of visibility for class members:
No
Access protection: An example
//This program shows all combinations of the access control modifiers
//In this program, we define two packages and five classes.
MyPackage1:
class X
class Y extends X
class A
MyPackage2:
class Z extends X
class B
Access protection: An example
// Defining package MyPackage1
package MyPackage1;
public class X {
int n = 1;
private int p = 2;
protected int q = 3;
public int r = 4;
// A constructor of the class protection
public X() {
[Link]("I am constructor from class X:");
[Link]("n="+n);
[Link]("p="+p);
[Link]("q="+q);
[Link]("r="+r);
}
}
//Save this as [Link] in Mypackage1 directory
Access protection: An example
package MyPackage1
class Y extends X {
Y() {
[Link]("I am constructor from class Y:");
[Link]("n="+n);
[Link]("p="+p);
// Error p is a private member of X. Not accessible outside X.
[Link]("q="+q); // Protected is accessible
[Link]("r="+r); // public is accessible
}
}
//Save this as [Link] in Mypackage1 directory
Access protection: An example
// Defining package MyPackage1
package MyPackage1
public class X {
int n = 1;
private int p = 2;
protected int q = 3;
public int r = 4;
// A constructor of the class protection
}
//Save this as [Link] in Mypackage1 directory
//Save this as [Link] in Mypackage1 directory
class A { // class with default protection
A() { // default constructor with default access
X x = new X() // create an object of class X
[Link]("Same package constructor ....");
[Link]("n from A"+x.n);
// Default variable is accessible in the same package
[Link]("p from A"+x.p); // Error
[Link]("q from A"+x.q); // Error protection
[Link]("r from A"+x.r); // OK: public
}
}
Access protection: An example
// Defining package MyPackage1
package MyPackage1
public class X {
int n = 1;
private int p = 2;
protected int q = 3;
public int r = 4;
// A constructor of the class protection
}
//Save this as [Link] in Mypackage1 directory
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Revisit the Abstract Class
Abstract class concept in Java
• We have discussed a number of programs with class Circle.
• Suppose, we want to have a number of other shapes namely Ellipse, Rectangle, Triangle,
etc.
• All these shapes can be placed in a package, say, myShapes.
• Note that all these shape classes have basic operations, namely area() and
circumference().
• Lets see, how the above can be realized better using abstract class concept in Java.
Geometry
Circle ?
However, this is not possible, as Java does not support multiple inheritance.
Java’s solution to this problem is called interface.
Interfaces in Java
Multiple inheritance and interface
Methods declared in an interface are always public and abstract, therefore Java
compiler will not complain if you omit both keywords. Static methods cannot be declared
in the interfaces – these methods are never abstract and do not express behavior of objects.
Basic concept of inheritance
Using the keyword interface, one can define an abstract class.
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are defined without any body.
interface callMe {
Example: void call (int p);
}
Multiple inheritance in Java
• Once an interface is defined, any number of classes can implement an interface.
Interface
Class1 Class n
Class
Interface : An example
Properties of interface
Interface must be declared with All interface methods are All variables defined in an interface Interface methods must not
the keyword interface. implicitly public and abstract. In is public, static and final. be static.
other words, you do not need to In other words, interfaces can
actually type the public or abstract declare only constants, no instance
modifiers in the method variables.
declaration, but method is still
always public and abstract.
Because interface methods are An interfaces can extend one or An interface cannot implement interface types can be used
abstract, they cannot be more other interfaces. another interface or class. polymorphically.
marked final.
Syntax for defining interface
Following is the syntax to define an interface
Syntax
class className [extends superClassName]
{
[implements interfaceName1, interfaceName2, ...]
{
Class body
}
}
Implementation of classes with interface
Implementation of classes with interface: Example
interface GeoAnalyzer {
final static float pi = 3.142F;
float area( );
float perimeter( );
}
class Circle implements GeoAnalyzer {
float radius;
Circle(float r) {
radius = r;
}
public float area( ) {
return (pi*radius*radius);
}
public float perimeter( ) {
return (2*pi*radius);
}
}
Implementation of classes with interface: Example
class Rectangle implements GeoAnalyzer
class Ellipse implements GeoAnalyzer {
{
float major;
float length;
float minor;
float width;
Ellipse(float m, flaot n) {
Rectangle(float l, float w) {
major = m;
length = l;
minor = n;
width = w;
}
}
public float area( ) {
public float area() {
return(pi*major*minor);
return(length*width);
}
}
public float perimeter( ) {
public float perimeter( ) {
return(pi*(major+minor);
return(2*(length+width));
}
}
}
}
Implementation of classes with interface: Example
class Geometry
{
static void display(float x, float y) {
[Link]("Area = " + x + "Perimeter = " + y);
}
public static void main(String args[ ]) {
Circle c = new Circle(5.2);
Ellipse e = new Ellipse(4.5, 3.6);
Rectangle r = new Rectangle(6.5, 4.3);
GeoAnalyzer geoItem;
geoItem = c;
display([Link](), [Link]());
geoItem = e;
display([Link](), [Link]());
geoItem = r;
display([Link](), [Link]());
}
}
Implementation of classes with interface: Example
Inheritance with Interface
Extending interface
• Interface can inherit from other interface.
• Interface can also multiply inherits.
interface Constants { interface Chemistry extends
double velOfLight = 3.0e+10; Constants
String unitVelOfLight = "m/s"; {
.... .... .... .... ..... ..... ...... .....
} ..... ..... ...... .....
interface Physics { }
void quantumLaw(); interface lawOfPysics extends
... ... ... ... Constants, Physics
{
} ..... ..... ...... .....
..... ..... ...... .....
}
OBJECT ORIENTED PROGRAMMING WITH JAVA
Interfaces in Java – II
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Various Types of Interface
Some of Java's Most used interfaces
Iterator • To run through a collection of objects without knowing how the objects
are stored, for example, in array, list, bag, or set.
Serializable • Pack a web of objects such that it can be send over a network or stored to
disk. A naturally later be restored as a web of objects Comparable.
Comparable • To make a total order of objects, for example, 3, 56, 67, 879, 3422, 34234
Iterator interface
The Iterator interface in the package [Link] is a basic iterator that works on
collections.
package [Link].*;
public interface Iterator {
public abstract boolean hasNext(); // Check, if the list has more
Object next(); // Return the next element
void remove(); // optional throws exception
}
// use an iterator
myShapes = getSomeCollectionOfShapes(); // Has set of objects
Iterator iter = [Link]();
while ([Link]()) {
Shape s = (Shape)[Link](); // downcast
[Link]();
}
Cloneable interface
• A class X that implements the Cloneable interface tells that the objects of class X can be
cloned.
• The interface is empty, that is, it has no method.
• Returns an identical copy of an object.
A shallow copy, by default.
A deep copy is often preferable.
• Prevention of cloning
Necessary, if unique attribute, for example, database lock or open file reference.
Not sufficient to omit to implement Cloneable.
• Sub classes might implement it.
}
// write to and read from disk
import [Link].*;
public class SerializeDemo{
Car myToyota, anotherToyota;
myToyota = new Car("Toyota", "Carina", 42312); A class X that implements the
ObjectOutputStream out = getOutput();
[Link](myToyota); Serializable interface tells
ObjectInputStream in = getInput(); clients that X objects can be
anotherToyota = (Car)[Link]();
} stored on a file or other
persistent media.
Returns a negative integer, zero, or a positive integer as this object is less than,
equal to, or greater than the specified object.
package [Link].*;
public interface Comparable {
int compareTo(Object o);
}
Comparable interface: Example
public class IPAddress implements Comparable{
private int[] n; // here IP stored, e.g., [Link]
/** The Comparable interface */
public int compareTo(Object o){
IPAddress other = (IPAddress) o; // downcast
int result = 0;
for(int i = 0; i < [Link]; i++){
if ([Link](i) < [Link](i)){
result = -1;
break;
}
if ([Link](i) > [Link](i)){
result = 1;
break;
}
}
return result;
}
}
Some Salient Points
Defining an interface
• Defining an interface is similar to creating a new class.
• An interface definition has two components: the interface declaration and the interface
body.
interfaceDeclaration
{
interfaceBody
}
If you do not specify that your interface is public, your interface will be accessible only
to classes that are defined in the same package as the interface.
Implementing an interfaces
To implement an interface, include the implements clause in a class definition, and then
create the methods required by the interface. The general form of a class that includes the
implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma.
If a class implements two interfaces that declare the same method, then that method will be
used by the clients of either interface.
The methods that implement an interface must be declared public.
Implementing interfaces: An example
Example: A class that implements, say Callback interface:
Here, the class Incomplete does not implement callback( ) and must be declared as
abstract. Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.
Nested interfaces
import [Link];
This program makes use of
interface SharedConstants {
int NO = 0; one of Java’s standard
int YES = 1; classes: Random, which
int MAYBE = 2; provides pseudorandom
int LATER = 3; numbers.
int SOON = 4;
int NEVER = 5;
}
Variables in interfaces
• For example, assume that two interfaces called Alpha and Beta are implemented by a class called
MyClass. What happens if both Alpha and Beta provide a method called reset( ) for which both declare
a default implementation? Is the version by Alpha or the version by Beta used by MyClass? Or, consider
a situation in which Beta extends Alpha. Which version of the default method is used? Or, what if
MyClass provides its own implementation of the method?
• To handle these and other similar types of situations, Java defines a set of rules that resolves such
conflicts.
Multiple inheritance issues
Rules.
• First, in all cases, a class implementation takes priority over an interface default implementation.
• Thus, if MyClass provides an override of the reset( ) method, MyClass’ version is used.
• This is the case even if MyClass implements, say both Alpha and Beta. In this case, both
defaults are overridden by MyClass’ implementation.
• Second, in cases in which a class implements two interfaces that both have the same default method,
but the class does not override that method, then an error will occurs. Continuing with the example, if
MyClass implements both Alpha and Beta, but does not override reset( ), then an error will
occur.
Multiple inheritance issues
Rules.
• In cases, one interface inherits another, with both defining a common default
method, the inheriting interface’s version of the method takes precedence.
Therefore, continuing the example, if Beta extends Alpha, then Beta’s
version of reset( ) will be used.
• For example, if Beta wants to refer to Alpha’s default for reset( ), it can use this
statement:
[Link]();
Questions to think…