Packages and Interfaces (Module 5) Java
Packages and Interfaces (Module 5) Java
MODULE-5
Packages and Interfaces: Packages, Access Protection, Importing Packages,
Interfaces,
Exception handling: Exception handling in Java. Packages, Access Protection,
Importing Packages, Interfaces.
3.1 Packages
Packages are containers for classes that are used to keep the class name space compartmentalized.
Through the use of the interface keyword, Java allows to fully abstract the interface from its
implementation.
Using interface, we can specify a set of methods that can be implemented by one or more classes.
The interface, itself, does not actually define any implementation. A class can implement more than
one interface.
3.1.1 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.
It is possible to define classes inside a package that are not accessible by code outside that package.
We can define class members that are only exposed to other members of the same package.
Defining a Package
To create a package ,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 we skip the package statement, the class names are put into the default package, which has no
name.
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;
The General form of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]];
Finding Packages and CLASSPATH
How does the Java run-time system know where to look for packages that we create? The answer has
three parts.
First, by default, the Java run-time system uses the current working directory as its starting point.
Second, we can specify a directory path or paths by setting the CLASSPATH environmental variable.
Third, we can use the -classpath option with java and javac to specify the path to our classes.
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
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);
for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Different
package No No Yes Yes
subclass
Different
package No No No Yes
non-subclass
An Access Example
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);
}
}
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
package p2;
class Protection2 extends p1.Protection
{
Protection2()
{
System.out.println("derived other package constructor");
// System.out.println("n = " + n);
package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// System.out.println("n = " + p.n);
The import statement is used to bring certain classes, or entire packages, into visibility. import
statements occur immediately following the package statement (if it exists) an before any class
definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
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 (.).
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.
import java.lang.*;
import java.util.*;
class MyDate extends Date
{
}
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,
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.
TestBalance imports MyPack and is then able to make use of the Balance class:
import MyPack.*;
class TestBalance
When the Java run-time system detects the attempt to divide by zero, it constructs a new exception
object and then throws this exception.
This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be
caught by an exception handler and dealt with immediately.
Here we don’t have any exception handlers of our own, so the exception is caught by the default
handler provided by the Java run-time system.
Any exception that is not caught by our program will ultimately be processed by the default handler.
The default handler displays a string describing the exception, prints a stack trace from the point at
which the exception occurred, and terminates the program.
Here is the exception generated when this example is executed: java.lang.ArithmeticException: / by
zero at Exc0.main(Exc0.java:4)
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
class HandleError
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++)
{
try
{
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e)
{
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
output:
C:\>java MultiCatch
a=0
DEPT OF ECE, VTU MH
Programming in Java Module 4
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e)
{
System.out.println("This is never reached.");
}
}
}
If this program is compiled , we will receive an error message stating that the second catch statement
is unreachable because the exception has already been caught.
Since ArithmeticException is a subclass of Exception, the first catch statement will handle all
Exception-based errors, including ArithmeticException.
This means that the second catch statement will never execute. To fix the problem, reverse the order
of the catch statements.
The try statement can be nested. That is, a try statement can be inside the block of another try.
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==1) a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
DEPT OF ECE, VTU MH
Programming in Java Module 4
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
3.3.7 Throw
It is possible for your program to throw an exception explicitly, using the throw statement.
The general form of throw is shown here:
throw ThrowableInstance;
If a method is capable of causing an exception that it does not handle, it must specify this behavior so
that callers of the method can guard themselves against that exception.
We can do this by including a throws clause in the method’s declaration.
3.3.8 throws
A throws clause lists the types of exceptions that a method might throw
.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
//body of method
}
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
3.3.9 finally
finally creates a block of code that will be executed after a try/catch block has completed and before
the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches the
exception
class FinallyDemo
{
static void procA()
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally
{
System.out.println("procA's finally");
}
}
static void procB()
{
try
{
System.out.println("inside procB");
return;
}
finally
{
System.out.println("procB's finally");
}
}
static void procC()
{
try
{
System.out.println("inside procC");
}
finally
{
System.out.println("procC's finally");
}
}
public static void main(String args[])
{
try
{
procA();
}
catch (Exception e)
DEPT OF ECE, VTU MH
Programming in Java Module 4
{
System.out.println("Exception caught");
}
procB();
procC();
}
}
Here is the output generated by the preceding program: inside procA procA’s finally Exception caught
inside procB procB’s finally inside procC procC’s finally
Inside the standard package java.lang, Java defines several exception classes. The most general of
these exceptions are subclasses of the standard type
RuntimeException
if the method can generate one of these exceptions and does not handle it itself. These are called
checked exceptions.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompat
type.
ClassCastException Invalid cast
EnumConstantNotPresentException An attempt is made to use an undefined enumera
value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
NullPointerException Invalid use of a null reference
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contain
completed stack trace
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception,
null is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace,
one element at a time, as an array of
class ChainExcDemo
DEPT OF ECE, VTU MH
Programming in Java Module 4
{
static void demoproc()
{
//create an exception
NullPointerException e =new NullPointerException("top layer");
//add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
//display top level exception
System.out.println("Caught: " + e);
//display cause exception
System.out.println("Original cause: " + e.getCause());
}
}
}