Module-4
Module-4
In java packages are used to avoid naming conflict and to control the access of
class, interface, sub-classes, etc. A package can be defined as a group of similar
types of classes, sub-classes, interfaces or enumerations, etc. while using
packages it becomes easier to locate or find the related classes and packages
provides a good structure or outline of the project with a huge amount of
classes and files.
Packages are divided into two parts:
import java.util.Arrays;
Output:
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 Short Package Example
// A simple package class AccountBalance {
package MyPack; public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
double bal; current[0] = new Balance("K. J. Fielding", 123.23);
Balance(String n, double b) { current[1] = new Balance("Will Tell", 157.02);
name = n; current[2] = new Balance("Tom Jackson", -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);
}
}
}
This is file Protection.java: This is file Derived.java:
package p1;
public class Protection { package p1;
class Derived extends Protection {
int n = 1; Derived() {
private int n_pri = 2; System.out.println("derived constructor");
protected int n_pro = 3; System.out.println("n = " + n);
public int n_pub = 4; // class only
// System.out.println("n_pri = "4 + n_pri);
public Protection() { System.out.println("n_pro = " + n_pro);
System.out.println("base constructor"); System.out.println("n_pub = " + n_pub);
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 Protection.java: This is file SamePackage.java:
package p1; package p1;
class SamePackage {
public class Protection {
SamePackage() {
int n = 1; Protection p = new Protection();
private int n_pri = 2; System.out.println("same package
protected int n_pro = 3; constructor");
System.out.println("n = " + p.n);
public int n_pub = 4;
// class only
public Protection() { // System.out.println("n_pri = " + p.n_pri);
System.out.println("base constructor"); System.out.println("n_pro = " + p.n_pro);
System.out.println("n = " + n); System.out.println("n_pub = " + p.n_pub);
}
System.out.println("n_pri = " + n_pri);
}
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
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);
}
}
This is file 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);
}
}
// Demo package p1. // Demo package p2.
package p1; package p2;
// Instantiate the various classes in p1. // Instantiate the various classes in p2.
public class Demo { public class Demo {
public static void main(String args[]) {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
Protection ob1 = new Protection(); OtherPackage ob2 = new OtherPackage();
Derived ob2 = new Derived(); }
SamePackage ob3 = new SamePackage(); }
}
}
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|*);
package MyPack;
/* Now, the Balance class, its constructor, import MyPack.*;
and itsshow() method are public. class TestBalance {
This means that they canbe used by non-subclass public static void main(String args[]) {
code outside their package. /* Because Balance is public,
*/ you may use Balance class
public class Balance { and call its constructor. */
String name; Balance test = new Balance("J. J. Jaspers", 99.88);
double bal; test.show(); // you may also call show()
public Balance(String n, double b) { }
name = n; }
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
Interfaces
• Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
• That is, using interface, you can specify what a class must do, but not how it
does it.
• Interfaces are syntactically similar to classes, but they lack instance variables,
and their methods are declared without any body.
• Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.
• To implement an interface, a class must create the complete set of methods
defined by the interface. However, each class is free to determine the details of
its own implementation.
• By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}
} }
}
} The output from this program is shown here:
callback called with 42
Another version of callback
p squared is 1764
Partial Implementations
If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract. For example:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Using try and catch
Although the default exception handler provided by the Java run-time system is
useful for debugging, you will usually want to handle an exception yourself.
Doing so provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating. Most users would
be confused (to say the least) if your program stopped running and printed a stack
trace whenever an error occurred! Fortunately, it is quite easy to prevent this.
To guard against and handle a run-time error, simply enclose the code that you
want to monitor inside a try block.
Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block. A try block must be followed by catch blocks or
finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can
throw a exception, enclosed them in try block and handle that exception
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try
block can have several catch blocks associated with it. You can catch different exceptions in different
catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that particular
exception executes. For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) object e)
{
//error handling code
}
Example
class Exc2 { Output:
public static void main(String args[]) { Division by zero.
int d, a; After catch statement.
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Example of Multiple catch blocks
catch(ArithmeticException e){
class Example2{ System.out.println("Warning: ArithmeticException");
}
public static void main(String args[]){
catch(ArrayIndexOutOfBoundsException e){
try{ System.out.println("Warning: ArrayIndexOutOfBoundsException");
int a[]=new int[7]; }
a[4]=30/0; catch(Exception e){
System.out.println("Warning: Some Other exception");
System.out.println("First print statement in try block"); }
} System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
Example
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.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
Nested try Statements
throw
• So far, you have only been catching exceptions that are thrown by the Java
run-time system.
• However, 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;
Demonstrate throw.
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.
• You do this by including a throws clause in the method’s declaration. 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:
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler.
Unchecked Exceptions
• Java defines several exception classes inside the standard package java.lang.
• The most general of these exceptions are subclasses of the standard type RuntimeException.
• Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
• Java defines several other types of exceptions that relate to its various class libraries.
SecurityException
Attempt to violate security.
Exception Description
IllegalAccessException IllegalAccessException
NoSuchFieldException
A requested field does not exist.
Here you can also define your own exception classes by extending Exception. These
exception can represents specific runtime condition of course you will have to throw them
yourself, but once thrown they will behave just like ordinary exceptions.