KEMBAR78
Packages and Interfaces (Module 5) Java | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
11 views17 pages

Packages and Interfaces (Module 5) Java

This document covers Java programming concepts including packages, interfaces, access protection, and exception handling. It explains how to create and manage packages, the visibility of class members, and the use of import statements. Additionally, it details exception handling mechanisms in Java, including the use of try-catch blocks and the hierarchy of exception types.

Uploaded by

mohan87220
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)
11 views17 pages

Packages and Interfaces (Module 5) Java

This document covers Java programming concepts including packages, interfaces, access protection, and exception handling. It explains how to create and manage packages, the visibility of class members, and the use of import statements. Additionally, it details exception handling mechanisms in Java, including the use of try-catch blocks and the hierarchy of exception types.

Uploaded by

mohan87220
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/ 17

Programming in Java Module 4

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.

DEPT OF ECE, VTU MH


Programming in Java Module 4

A Short Package Example

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.

3.2 Access Protection


Packages add another dimension to access control.
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.
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
The three access specifiers, private, public, and protected, provide a variety of ways to produce the
many levels of access required by these categories.
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.
DEPT OF ECE, VTU MH
Programming in Java Module 4
If we want to allow an element to be seen outside our current package, but only to classes that
subclass our class directly, then declare that element protected.

Private No Modifier Protected Public

Same class yes yes yes yes


Same
package No Yes Yes Yes
subclass
Same
package No Yes Yes Yes
non-subclass

Different
package No No Yes Yes
subclass

Different
package No No No Yes
non-subclass

An Access Example

This 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.

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

This is file Derived.java:


DEPT OF ECE, VTU MH
Programming in Java Module 4

package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);

// System.out.println("n_pri = "4 + n_pri);

System.out.println("n_pro = " + n_pro);


System.out.println("n_pub = " + n_pub);
}
}

This is file SamePackage.java:

package p1;

class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);

// System.out.println("n_pri = " + p.n_pri);

System.out.println("n_pro = " + p.n_pro);


System.out.println("n_pub = " + p.n_pub);
}
}

Following is the source code for the other package, p2.


The first class, Protection2, is a subclass of p1.Protection. This grants access to all of
p1.Protection’s variables except for n_pri (because it is private) and n, the variable declared with the
default protection.
the default only allows access from within the class or the package, not extra-package subclasses.
the class OtherPackage has access to only one variable, n_pub, which was declared public.

This is file Protection2.java:

package p2;
class Protection2 extends p1.Protection
{
Protection2()
{
System.out.println("derived other package constructor");
// System.out.println("n = " + n);

// System.out.println("n_pri = " + n_pri);


DEPT OF ECE, VTU MH
Programming in Java Module 4

System.out.println("n_pro = " + n_pro);


System.out.println("n_pub = " + n_pub);
}
}

This is file OtherPackage.java:

package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// System.out.println("n = " + p.n);

// System.out.println("n_pri = " + p.n_pri);

// System.out.println("n_pro = " + p.n_pro);

// System.out.println("n_pub = " + p.n_pub);


}
}
.
package p1;

// Instantiate the various classes in p1.


public class Demo
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}

// Demo package p2. package p2;


public class Demo
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}

3.3 Importing Packages


DEPT OF ECE, VTU MH
Programming in Java Module 4

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 (.).

This code fragment shows both forms in use:


import java.util.Date;
import java.io.*;.

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,

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

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

DEPT OF ECE, VTU MH


Programming in Java Module 4
{
public static void main(String args[])
{
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}

Exception Handling in java


An exception is a run-time error. Languages that do not support exception handling, errors must be
checked and handled manually—typically through the use of error codes, and so on.
Java’s exception handling avoids handling problems manually and, in the process, brings run-time
error management into the object oriented world.

3.3.1 Exception-Handling Fundamentals


A Java exception is an object that describes an exceptional (that is, error) condition that has occurred
in a piece of code.
When an exceptional condition arises, an object representing that exception is created and thrown in
the method that caused the error.
That method may choose to handle the exception itself, or pass it on. Either way, at some point, the
exception is caught and processed.Exceptions can be generated by the Java run-time system, or they
can be manually generated by your code.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Briefly, here is how they work. Program statements that create exceptions are contained within a try
block.
If an exception occurs within the try block, it is thrown.we can catch this exception (using catch) and
handle it .
System-generated exceptions are automatically thrown by the Java run-time system. To manually
throw an exception, use the keyword throw.Any exception that is thrown out of a method must be
specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.

This is the general form of an exception-handling block:


try
{
//block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
//exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)

DEPT OF ECE, VTU MH


Programming in Java Module 4
{
//exception handler for ExceptionType2
}
//...
finally
{
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.

3.3.2 Exception Types


All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of
the exception class hierarchy.
Immediately below Throwable are two subclasses that partition exceptions into two distinct
branches.
One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch.
There is an important subclass of Exception, called RuntimeException. Exceptions of this type are
automatically defined for the programs that you write and include things such as division by zero and
invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected to be caught
under normal circumstances by your program.
Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the
run-time environment, itself. Stack overflow is an example of such an error

3.3.3 Uncaught Exceptions

This program includes an expression that intentionally causes a divide-by-zero error:


class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

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)

3.3.4 Using try and catch

DEPT OF ECE, VTU MH


Programming in Java Module 4
Although the default exception handler provided by the Java run-time system is useful for debugging,
we should handle an exception our self.
Doing so provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
To handle a run-time error, simply enclose the code inside a try block.
Immediately following the try block, include a catch clause that specifies the exception type to catch

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

This program generates the following output:


Division by zero.
After catch statement.

A try and its catch statement form a unit.


The scope of the catch clause is restricted to those statements specified by the immediately preceding
try statement.
A catch statement cannot catch an exception thrown by another try 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)
{

DEPT OF ECE, VTU MH


Programming in Java Module 4
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}

3.3.5 Multiple catch Clauses


More than one exception could be raised by a single piece of code.
To handle this type of situation, we can specify two or more catch clauses, each catching a different
type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one whose type
matches that of the exception is executed.

The following example traps two different exception types:

// Demonstrate multiple catch statements.

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

Array index oob: java.lang.ArrayIndexOutOfBoundsException:42 After try/catch blocks.

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.

3.3.6 Nested try 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);
}
}
}

When we execute the program with no command-line arguments, a divide-by-zero exception is


generated by the outer try block.
Execution of the program with one command-line argument generates a divide-by-zero exception
from within the nested try block.
Since the inner block does not catch this exception, it is passed on to the outer try block, where it is
handled.
If we execute the program with two command-line arguments, an array boundary exception is
generated from within the inner try block.
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

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;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.


Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object,
cannot be used as exceptions.
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
DEPT OF ECE, VTU MH
Programming in Java Module 4
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

First, main( ) sets up an exception context and then calls demoproc( ).


The demoproc( ) method then sets up another exceptionhandling context and immediately throws a
new instance of NullPointerException, which is caught on the next line.
The exception is then rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo throws

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

Here is the output generated by running this example program:


inside throwOne
DEPT OF ECE, VTU MH
Programming in Java Module 4
caught java.lang.IllegalAccessException: demo

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

3.3.10 Java’s Built-in Exceptions

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.

Java’s Unchecked RuntimeException Subclasses Defined in java.lang

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

• Java’s Checked Exceptions Defined in java.lang


Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract clas
interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.

DEPT OF ECE, VTU MH


Programming in Java Module 4
NoSuchMethodException A requested method does not exist.

3.3.11 Creating Your Own Exception Subclasses


It is possible to create to create our own exception types to handle situations specific to your
applications.
Just define a subclass of Exception
Your subclasses don’t need to actually implement anything—it is their existence in the type system
that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit those methods
provided by Throwable.
Thus, all exceptions, including those that we create, have the methods defined by Throwable
available to them.

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

3.3.12 Chained Exceptions


The chained exception feature allows you to associate another exception with an exception.
This second exception describes the cause of the first exception.
For example, imagine a situation in which a method throws an ArithmeticException because of an
attempt to divide by zero.
However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to
be set improperly.
To allow chained exceptions, two constructors and two methods were added to Throwable.
The constructors are shown here: Throwable(Throwable causeExc) Throwable(String msg, Throwable
causeExc)
These two constructors have also been added to the Error, Exception, and RuntimeException
classes.
The chained exception methods added to Throwable are getCause( ) and initCause( ). These
methods are shown.
Throwable getCause( )
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current exception. If there is no
underlying exception, null is returned.
The initCause( ) method associates causeExc with the invoking exception and returns a reference to
the exception.

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

The output from the program is shown here:


Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
In this example, the top-level exception is NullPointerException.
To it is added a cause exception, ArithmeticException. When the exception is thrown out of
demoproc( ), it is caught by main( ).
There, the top-level exception is displayed, followed by the underlying exception, which is obtained
by calling getCause( ).

3.3.13 Using Exceptions


Exception handling provides a powerful mechanism for controlling complex programs that have
many dynamic run-time characteristics.
It is important to think of try, throw, and catch as clean ways to handle errors and unusual
boundary conditions in your program’s logic.
Unlike some other languages in which error return codes are used to indicate failure, Java uses
exceptions. Thus, when a method can fail, have it throw an exception. This is a cleaner way to
handle failure modes.
One last point: Java’s exception-handling statements should not be considered a general
mechanism for non local branching. If you do so, it will only confuse your code and make it hard
to maintain.

DEPT OF ECE, VTU MH

You might also like