Java Programming
Unit – 3
Interfaces, Packages and Exceptions
Dr. Y. J. Nagendra Kumar
Professor of IT
Dean - Technology and Innovation Cell - GRIET
TABLE OF
CONTENTS
01 Interfaces
02 Packages
03 Exception Handling
Dr. Y. J. Nagendra Kumar - 2
Interfaces
Dr. Y. J. Nagendra Kumar - 3
Interfaces
● Java does not support multiple inheritance. That is, classes in java
cannot have more than one superclass.
● Java provides an alternate approach known as interfaces to support
the concept of multiple inheritance.
● Interfaces are syntactically similar to classes, but they define only
abstract methods and final fields.
● This means that interfaces do not specify any code to implement these
methods and data fields contain only constants.
● Once it is defined, any number of classes can implement an interface.
Also, one class can implement any number of interfaces.
Dr. Y. J. Nagendra Kumar - 4
Defining an Interface
● An interface is defined much like a class. This is the general form of an interface:
access interface name
{
type final-varname1 = value;
type final-varname2 = value;
// ...
type final-varnameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
}
Here, access is either public or not used
Dr. Y. J. Nagendra Kumar - 5
Interfaces
● Methods are, essentially, abstract methods
● Each class that includes an interface must implement all of the methods.
● Variables can be declared inside of interface declarations. They are implicitly
final and static, meaning they cannot be changed by the implementing class.
● All methods and variables are implicitly public if the interface, itself, is
declared as public.
Ex: interface shape
{
void area(int param);
}
Dr. Y. J. Nagendra Kumar - 6
Implementing Interfaces
● Once an interface has been defined, one or more classes can
implement that interface.
● To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface.
Syntax:
access class classname [extends superclass]
[implements interface [,interface...]]
{
// class-body
}
Dr. Y. J. Nagendra Kumar - 7
Interfaces contd.,
● Here, access is either public or not used. If a class implements more
than one interface, the interfaces are separated with a comma.
● The methods that implement an interface must be declared public.
● Also, the type signature of the implementing method must match
exactly the type signature specified in the interface definition.
Dr. Y. J. Nagendra Kumar - 8
Interfaces
class circle implements shape
{
// Implement shape's interface
public void area(int p)
{
[Link](“Area of Circle “+3.14*p*p);
}
}
Dr. Y. J. Nagendra Kumar - 9
Interfaces First Example
interface draw class interface1
{ final static double PI=3.14; { public static void main(String ar[])
double area(double d1,double d2); { triangle t=new triangle();
}
class triangle implements draw circle c=new circle();
{ draw d;
public double area(double d1,double d2)
{ return d1*d2/2; } d=t;
} [Link]("Area of Triangle“ +[Link](22,10));
class circle implements draw
{
public double area(double d1,double d2) d=c;
{ return PI*d1*d1; } [Link]("Area of Circle “+[Link](10,0));
} }
}
Dr. Y. J. Nagendra Kumar - 10
Interfaces Second Example
class student class test extends student
{ {
int rollno; double m1,m2;
void getno(int a)
{ void getmarks(double a,double b)
rollno=a; {
} m1=a; m2=b;
void putno() }
{
[Link](" Roll Number : "+rollno); void putmarks()
} {
} [Link]("M1 : "+m1+" M2 : "+m2);
}
}
Dr. Y. J. Nagendra Kumar - 11
Interfaces Second Example contd.,
interface sports void show()
{ { total=m1+m2+spwt;
final static double spwt=10; putno();
void putspwt(); putmarks();
} putspwt();
class result extends test implements sports [Link]("Total Marks :"+total);
{ }
double total; }
public void putspwt() class interface2
{ { public static void main(String ar[])
[Link]("Sports Marks Weightage { result r=new result(); [Link](786);
: "+spwt); [Link](78.5,65.25); [Link]();
} }
}
Dr. Y. J. Nagendra Kumar - 12
Interfaces Can Be Extended
◼ One interface can inherit another by use of the keyword extends.
◼ When a class implements an interface that inherits another interface, it
must provide implementations for all methods defined within the
interface inheritance chain
Dr. Y. J. Nagendra Kumar - 13
Interfaces Can be extended Example contd.,
public void meth2()
interface A {
{ void meth1(); [Link]("Implement meth2().");
void meth2(); }
} public void meth3()
interface B extends A {
{ void meth3();
[Link]("Implement meth3().");
}
class MyClass implements B }
{ public void meth1() }
{ class interface3
[Link]("Implement meth1()."); { public static void main(String arg[])
}
{ MyClass ob = new MyClass();
ob.meth1(); ob.meth2(); ob.meth3();
}
}
Dr. Y. J. Nagendra Kumar - 14
Difference between Interfaces and Abstract Classes
Feature Interface Abstract class
Multiple A class may implement A class may extend only one abstract
inheritance several interfaces. class.
An interface cannot
Default An abstract class can provide
provide any code at all,
implementation complete code, default code.
much less default code.
Both instance and static constants are
Constants Static final constants only
possible.
Dr. Y. J. Nagendra Kumar - 15
Packages
Dr. Y. J. Nagendra Kumar - 16
Packages
● Java provides a powerful means of grouping related classes and
interfaces together in a single unit called “packages “
● 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.
● If we omit the package statement, the class names are put into the
default package.
Dr. Y. J. Nagendra Kumar - 17
Package Syntax
● This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.
Ex: package MyPackage;
● The .class files for any classes we declare to be part of MyPackage
must be stored in a directory called MyPackage.
Dr. Y. J. Nagendra Kumar - 18
Packages Example
package infotech; class pack1
class balance {
{ String name; public static void main(String arg[])
double bal; {
balance(String n,double b) balance cur=new balance("Jeevan",22222.45);
{ name=n; bal=b; [Link]();
} }
void show() }
{ if(bal<0)
[Link](" --> ");
[Link](name+" "+bal);
}
}
Dr. Y. J. Nagendra Kumar - 19
Packages
● More than one file can include the same package statement. The
package statement simply specifies to which package the classes
defined in a file belong.
● We can create a hierarchy of packages.
● 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]];
Ex: package [Link];
Dr. Y. J. Nagendra Kumar - 20
Access Protection
● Packages act as containers for classes and other
subordinate packages.
● Classes act as containers for data and code.
Dr. Y. J. Nagendra Kumar - 21
Access Protection
Dr. Y. J. Nagendra Kumar - 22
Access Protection Example
package p1; package p1;
public class base
{ private int a=10; int b=20; class derived1 extends base
protected int c=30; {
public int d=40; derived1()
public base() {
{ [Link]("Derived 1 Constructor ...");
[Link]("Base Constructor ..."); // [Link]("a = "+a);
[Link]("a = "+a); [Link]("b = "+b);
[Link]("b = "+b); [Link]("c = "+c);
[Link]("c = "+c); [Link]("d = "+d);
[Link]("d = "+d); }
} }
}
Dr. Y. J. Nagendra Kumar - 23
Access Protection Example
package p1; package p1;
class other1
{ public class demo1
other1() {
{ public static void main(String ar[])
base k=new base(); {
[Link]("Other 1 Constructor ..."); base n=new base();
// [Link]("a = "+k.a); derived1 d1=new derived1();
[Link]("b = "+k.b); other1 o1=new other1();
[Link]("c = "+k.c); }
[Link]("d = "+k.d); }
}
}
Dr. Y. J. Nagendra Kumar - 24
Access Protection Example
package p2; package p2;
class derived2 extends [Link] class other2
{ {
derived2() other2()
{ {
[Link]("Derived 2 Constructor ..."); [Link] k=new [Link]();
// [Link]("a = "+a); [Link]("Other 2 Constructor ...");
// [Link]("b = "+b); // [Link]("a = "+k.a);
[Link]("c = "+c); // [Link]("b = "+k.b);
[Link]("d = "+d); // [Link]("c = "+k.c);
} [Link]("d = "+k.d);
} }
}
Dr. Y. J. Nagendra Kumar - 25
Access Protection Example
package p2;
public class demo2
{
public static void main(String ar[])
{
derived2 d2=new derived2();
other2 o2=new other2();
}
}
Dr. Y. J. Nagendra Kumar - 26
Importing Packages
● 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 and before any class definitions.
Dr. Y. J. Nagendra Kumar - 27
Importing Packages
● 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
(.). There is no practical limit on the depth of a package hierarchy.
● Finally, we specify either an explicit classname or a star (*), which
indicates that the Java compiler should import the entire package.
import [Link]; import [Link].*;
Dr. Y. J. Nagendra Kumar - 28
Importing Packages Example Contd.,
package mypack; import mypack.*;
public class import1
{ String name; class import2
double bal; {
public import1(String n,double b) public static void main(String arg[])
{ name=n; bal=b; {
} import1 cur=new import1("Jeevan",33333.45);
public void show() [Link]();
{ }
if(bal<0) }
[Link](" --> ");
[Link](name+" "+bal);
}
}
Dr. Y. J. Nagendra Kumar - 29
Exceptions
Dr. Y. J. Nagendra Kumar - 30
Uncaught Exceptions
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
Dr. Y. J. Nagendra Kumar - 31
Uncaught Exceptions
• Any exception that is not caught by your 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 output generated when this example is executed.
[Link]: / by zero
at [Link]([Link])
Dr. Y. J. Nagendra Kumar - 32
Uncaught Exceptions
class Exc1
{
static void subroutine()
{
int d = 0;
int a = 10 / d;
}
public static void main(String args[ ])
{
[Link]();
}
}
Dr. Y. J. Nagendra Kumar - 33
Uncaught Exceptions
• The resulting stack trace from the default exception handler shows
how the entire call stack is displayed:
• [Link]: / by zero
• at [Link]([Link])
• at [Link]([Link])
• As you can see, the bottom of the stack is main’s line 7, which is the
call to subroutine( ), which caused the exception at line 4.
Dr. Y. J. Nagendra Kumar - 34
Exception Class Hierarchy
Dr. Y. J. Nagendra Kumar - 35
Exception Class Hierarchy
-> All exception types are subclasses of the built-in class Throwable.
-> 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 Runtime
Exception.
Dr. Y. J. Nagendra Kumar - 36
Error
• Error: When a dynamic linkage failure or other hard failures
occurs then it throws an error.
• Simple programs can not catch or throw an error.
• Ex: Internal Error, Linkage error, Out of memory error, Stack
Overflow error etc.
Dr. Y. J. Nagendra Kumar - 37
Exception
• Exception indicates that a problem occurred but it is not a serious problem. An
exception is an abnormal condition that arises in a code sequence at run time.
• Runtime Exception: It is reserved for exceptions that indicate incorrect use of API.
• Unchecked Exceptions: Most exceptions are derived from Runtime Exception are
automatically available and they need not be included in try – catch block or in any
methods throws list.
Ex:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. ArrayStoreException
4. NegativeArraySizeException
5. NumberFormatException
6. NullPointerException Dr. Y. J. Nagendra Kumar - 38
Exception-Handling Fundamentals
• A Java exception is an object that describes an exceptional 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.
Dr. Y. J. Nagendra Kumar - 39
Exception-Handling Fundamentals
• Exceptions can be generated by the Java run-time system, or they can
be manually generated by your code.
• Exceptions thrown by Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java execution
environment.
• Manually generated exceptions are typically used to report some
error condition to the caller of a method.
Dr. Y. J. Nagendra Kumar - 40
Try, Catch, throw, throws & Finally
• Java exception handling is managed via five keywords: try, catch,
throw, throws and finally.
• Program statements that you want to monitor for exceptions are
contained within a try block.
• If an exception occurs within the try block, it is thrown. Your code can
catch this exception (using catch) and handle it in some rational
manner.
Dr. Y. J. Nagendra Kumar - 41
Try, Catch, throw, throws & Finally
• 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 before a method returns
is put in a finally block.
Dr. Y. J. Nagendra Kumar - 42
Exception Handling Mechanism Syntax
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) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
Dr. Y. J. Nagendra Kumar - 43
Unchecked Exceptions
class excep1
{ public static void main(String ar[])
{
int a=10;
int b=0;
try
{ a=a/b;
[Link]("This will not be printed");
}
catch(ArithmeticException ae)
{
[Link]("Division by 0 error... change the value");
}
[Link]("Quittting");
}
}
Dr. Y. J. Nagendra Kumar - 44
Checked Exceptions
CheckedExceptions: CheckedExceptions must be included in try-
catch or in a methods throws list.
Ex:
1. ClassNotFoundException
2. IOException
3. SQLException
4. NoSuchMethodException etc.,
Dr. Y. J. Nagendra Kumar - 45
Checked Exceptions
public class excep3
{
public static void main(String ar[])
{
try
{
Class c=[Link](ar[0].trim());
String name=[Link]();
Class sc=[Link]();
String sname=[Link]();
[Link]("Name is : "+name+" and SuperClass name is :"+sname);
}
catch(ClassNotFoundException cnf)
{ [Link]("No such Class");
}
}
}
Dr. Y. J. Nagendra Kumar - 46
Multiple catch Clauses
• In some cases, 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.
• After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
Dr. Y. J. Nagendra Kumar - 47
Multiple Catch
public class excep4
{
public static void main(String ar[])
{ try
{
int n=[Link];
int x[]=new int[-3];
if(n>0)
{
int m=[Link](ar[0]);
[Link]("Given number is : "+m/(m-n));
}
}
catch(NumberFormatException nfe)
{
[Link]("Number format exceptionnnn: "+nfe);
}
Dr. Y. J. Nagendra Kumar - 48
Multiple Catch (contd.,)
catch(ArrayIndexOutOfBoundsException ai)
{
[Link]("Array index is out of range ");
}
catch(ArithmeticException ae)
{
[Link]("Divide by 0 errorrrr");
}
catch(NegativeArraySizeException nase)
{
[Link]("Negative size........");
}
catch(Exception e)
{
[Link]("Exceptionnnn");
}
}
}
Dr. Y. J. Nagendra Kumar - 49
Nested try Statements
• The try statement can be nested. That is, a try statement can be inside the
block of another try.
• Each time a try statement is entered, the context of that exception is pushed
on the stack.
• If an inner try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers
are inspected for a match.
• This continues until one of the catch statements succeeds, or until all of the
nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system will handle the
exception.
Dr. Y. J. Nagendra Kumar - 50
Nested Try
class NestTry
{ public static void main(String args[])
{ try
{ int a = [Link];
int b = 12 / a;
[Link]("a = " + a);
try
{ if(a==1) a = a/(a-a);
String s=args[4];
}
catch(ArrayIndexOutOfBoundsException e)
{ [Link]("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{ [Link]("Divide by 0: " + e);
}
}
} Dr. Y. J. Nagendra Kumar - 51
throw
• We have only been catching exceptions that are thrown by the Java
run-time system.
• However, it is possible for our program to throw an exception
explicitly, using the “throw” statement.
• Syntax: throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
Dr. Y. J. Nagendra Kumar - 52
throw
• Simple types, such as int or char, as well as non-Throwable classes, such as
String and Object, cannot be used as exceptions.
• There are two ways we can obtain a Throwable object: using a parameter
into a catch clause, or creating one with the new operator.
• The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed.
Dr. Y. J. Nagendra Kumar - 53
Throw (Predefined Exceptions)
class ThrowDemo
{ static void throwfunction()
{ try
{ throw new ArithmeticException();
}
catch(ArithmeticException e)
{ [Link]("Caught inside throwfunction.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{ try
{ throwfunction();
}
catch(ArithmeticException e)
{ [Link]("Recaught: " + e);
}
}
}
Dr. Y. J. Nagendra Kumar - 54
Throw (User-defined Exceptions)
class userdefined class UserException extends Exception
{ static void throwfun(int a) throws UserException {
{ if(a<0) private int x;
throw new UserException(a);
[Link]("Normal Exit"); UserException(int a)
} {
public static void main(String args[]) x=a;
{ try }
{ throwfun(10);
throwfun(-5); public String toString()
} {
catch(UserException ue) return "IT students raised this exception "+x;
{ }
[Link]("Exception caught: " + ue); }
}
}
}
Dr. Y. J. Nagendra Kumar - 55
Throws clause
• 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 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 necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.
• All other exceptions that a method can throw must be declared in the
throws clause.
• If they are not, a compile-time error will result.
Dr. Y. J. Nagendra Kumar - 56
Throws clause
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
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
Dr. Y. J. Nagendra Kumar - 57
Throws Clauses
class throwsdemo
{
static void proc() throws ClassNotFoundException
{
Class c=[Link]("[Link]");
if(c==null)
throw new ClassNotFoundException();
[Link]("Class Found" +c);
}
public static void main(String ar[])
{ try
{ proc();
}
catch(ClassNotFoundException cnf)
{ [Link]("Class not foundddd");
}
}
}
Dr. Y. J. Nagendra Kumar - 58
Finally Clause
• finally creates a block of code that will be executed after a
try/catch block has completed
• 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.
Dr. Y. J. Nagendra Kumar - 59
Finally Clause
• This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a
method.
• The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
Dr. Y. J. Nagendra Kumar - 60
Finally
class FinallyDemo static void procB()
{ {
static void procA() try
{ {
try [Link]("inside procB");
{ return;
[Link]("inside procA"); }
throw new RuntimeException("demo"); finally
} {
finally [Link]("procB's finally");
{ }
[Link]("procA's finally"); }
}
}
Dr. Y. J. Nagendra Kumar - 61
Finally
static void procC() public static void main(String args[])
{ {
try try
{ {
[Link]("inside procC"); procA();
} }
finally catch (Exception e)
{ {
[Link]("procC's finally"); [Link]("Exception caught");
} }
} procB();
procC();
}
}
Dr. Y. J. Nagendra Kumar - 62
End of Unit III