Chapter 6
Chapter 6
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 java.util is a basic iterator that works on
collections.
package java.util.*;
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 = myShapes.iterator();
while (iter.hasNext()) {
Shape s = (Shape)iter.next(); // downcast
s.draw();
}
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 java.io.*;
public class SerializeDemo{
Car myToyota, anotherToyota;
myToyota = new Car("Toyota", "Carina", 42312); A class X that implements the
ObjectOutputStream out = getOutput();
out.writeObject(myToyota); Serializable interface tells
ObjectInputStream in = getInput(); clients that X objects can be
anotherToyota = (Car)in.readObject();
} 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 java.lang.*;
public interface Comparable {
int compareTo(Object o);
}
Comparable interface: Example
public class IPAddress implements Comparable{
private int[] n; // here IP stored, e.g., 125.255.231.123
/** The Comparable interface */
public int compareTo(Object o){
IPAddress other = (IPAddress) o; // downcast
int result = 0;
for(int i = 0; i < n.length; i++){
if (this.getNum(i) < other.getNum(i)){
result = -1;
break;
}
if (this.getNum(i) > other.getNum(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 java.util.Random;
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:
Alpha.super.reset();
Questions to think…
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Concept of Errors in Java
Errors in Java programs
Compile-
time Run-time
errors errors
and many
more…..
Compile-time errors: Examples
Class Error {
Public static void main (string args [ ]) {
system.out.print(“Can you find errors in me?”)
}
}
class AnotherError {
public void insert( ){
System.out.print(“To insert a text”);
}
}
Some common compile-time errors
• Missing semicolons.
• Missing (or mismatch of brackets) in classes and methods.
• Misspelling of identifiers or keywords.
• Missing double quotes in strings.
• Use of undeclared variables.
• Incomplete types in assignment / initialization.
• Bad references to objects.
and many more ….
Run-time errors: Examples
class Error {
public static void main (String args [ ]) {
int a = Integer.parseInt(args[0]};
int b = Integer.parseInt(args[1]};
int c = a/b;
System.out.println(“Value of c =“ + c);
}
}
Run-time trrors: Examples
class Error {
public static void main (String args [ ]) {
int a = Integer.parseInt(args[0]};
int b = Integer.parseInt(args[1]};
int c = a/b;
System.out.println(“Value of c =“ + c);
}
}
Some common run-time errors
• A user has entered invalid data.
• Dividing an integer by zero.
• Accessing an element that is out of the bounds of an array.
• Trying to store a value into an array of an incomplete class or type.
• Trying to cast an instance of a class to one of its subclasses. So errors are due to users,
• Trying to illegally change the state of a thread. programmers and physical
• Attempting use a negative size for an array. resources which are very
• Null object reference.
difficult to taken into
consideration while writing
• A file that needs to be opened cannot be found.
the programs …
• A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Examples:
Java Run-Time Environment throws an object called IllegalArumentType
when a method m(int x, int y) is called as m(1.5, 4);
Error Exception
• That method may choose to catch the exception and then can guard against premature exit
or may have a block of code to execute.
• Java exception handling is managed via five keywords:
try { …. }
catch { …. }
throw
throws
finally { …. }
Exception handling in Java
method
{
.
try{
statement(s) that may cause
Try block
exception(s)
throw exception object
}
catch {
statement(s) that handle the Catch block 1
exception(s)
}
catch {
statement(s) that handle the
exception(s) Catch block 2
}
fially {
statement(s) that execute on Finally block
exit of the exception handling
}
.
}
Exception handling in Java
Simple try- try with Multiple exceptions Exception with Throwing own Nested try-catch
catch multiple catch exit code exception block
Multiple Throws/
try with try-catch try within
try with a exception throw in try-
multiple with finally another try
single catch with one block
catch
catch
Simple try-catch block
Simple try-catch
method
{
.
try{
Try block
statement(s) that may cause
exception(s)
}
catch {
statement(s) that handle the Catch block 1
exception(s)
}
.
}
Simple try-catch: Example
class DivideZero {
static int anyFunction ( int x, int y ) {
int a = x/y;
return (a);
}
public static void main (String args [ ] ) {
int result = anyFunction (25, 0) ;
// Exception occurs here as y = 0
System.out.println ( “ Result : ” + result );
}
}
Simple try-catch: Example
Run time report while running the Application DivideZero
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
try- with Multiple catch
try with Multiple catch
method
{
.
try{
statement(s) that may cause Try block
exception(s)
throw exception object
}
catch {
statement(s) that handle the Catch block 1
exception(s)
}
.
.
.
catch {
statement(s) that handle the Catch block n
exception(s)
}
.
}
try with Multiple catch: Why?
class MultiCatch {
public static void main (String args[ ]) {
int i = args.length;
String myString = new String [i];
if(args[0].equals(“Java”))
System.out.println(“First word is Java !”);
System.out.println( “ Number of arguments = ” + i );
int x = 18/ i;
int y[ ] = {555, 999};
y[i] = x;
}
}
}
catch {
statement(s) that handle the Catch block
exception(s)
}
.
}
Multiple errors with single catch: An Example
class ExceptionTest {
public int j;
static void main (String args[ ] ) {
for (int i = 0; i < 4; i++ ) {
switch (i) {
case 0 :
int zero = 0;
j = 999/ zero;
break;
case 1:
int b[ ] = null;
j = b[0] ;
break;
case 2:
int c[ ] = new int [2];
j = c[10];
break;
case 3:
char ch = “Java”.charAt(9);
break;
}
}
}
}
Multiple errors with single catch: An Example
class ExceptionTest {
public int j;
static void main (String args[ ] ) {
for (int i = 0; i < 4; i++ ) {
switch (i) {
case 0:
int zero = 0;
j = 999/ zero; //Divide by zero
break;
case 1:
int b[ ] = null;
j = b[ 0]; //Null pointer error
break;
case 2:
int c = new int [2] ;
j = c[10]; // Array index is out-of-bound
break;
case 3:
char ch = “Java”.charAt(9) ; // String index is out-of-bound
break;
}
}
}
}
Multiple errors with single catch: An Example
class ExceptionTest {
public int j;
static void main (String args[ ] ) {
for (int i = 0; i < 4; i++ ) {
try {
switch (i) {
case 0 :
int zero = 0;
j = 999/ zero; // Divide by zero
break;
case 1:
int b[ ] = null;
j = b[0] ; // Null pointer error
break;
case 2:
int c = new int [2] ;
j = c[10]; // Array index is out-of-bound
break;
case 3:
char ch = “Java”.charAt(9) ;// String index is out-of-bound
break;
}
} catch (Exception e) {
System.out.println(“In Test case#”+i+ ”\n”);
System.out.println (e.getMessage() ); }
}
}
}
finally in try-catch
finally in try-catch
method
{
try{
statement(s) that may cause Try block
exception(s)
throw exception object
}
catch {
statement(s) that handle the Catch block
exception(s)
}
finally {
statement(s) that handle the
exception(s)
Finally block
}
.
}
finally in try-catch : An example
class FinallyDemo {
public static void main (String [ ] args ) {
int i = 0;
String greetings [ ] = { “Hello Twinkle !”, “Hello Java !”, “Hello World ! ”};
while ( i < 4) {
try {
System.out.println (greetings [i++] );
}catch (Exception e ) {
System.out.println (e.toString );// Message of exception e in String format
}
finally {
System.out.println(“You should quit and reset index value < 3 :”);
}
} // while ( )
} // main ( )
} // class
throw in try-catch
throw in try-catch
method
{
try{
statement(s) that may cause Try block
exception(s)
throw exception object
}
catch {
statement(s) that handle the Catch block
exception(s)
}
.
.
.
.
.
}
throw in try-catch : Mechanism
• 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.
• A throw clause lists the types of exceptions that a method might throw.
• All other exceptions that a method can throw must be declared in the throw clause.
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Nested try-catch
method
{.
..
try {
Statement(s) that may cause exception(s) try block
……….
try{
Statement(s) that cause another exception(s)
} Nested try block
catch{
Statement(s) that handle the exception(s)
}
}
catch{
2 public Throwable getCause(): Returns the cause of the exception as represented by a Throwable object.
3 public String toString(): Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace(): Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace(): Returns an array containing each element on the stack trace. The element at
5
index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace(): Fills the stack trace of this Throwable object with the current stack trace, adding to any
6
previous information in the stack trace.
User Defined Exceptions
Declaring your own exception
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class
• Syntax
import java.util.*;
class SimpleArrayList{
public static void main(String args[]){
int sum = 0;
float avg = 0;
ArrayList <Integer> l = new ArrayList<Integer>();
System.out.println("Enter the input ");
Scanner input = new Scanner(System.in);
while (input.hasNextInt()) {
l.add(input.nextInt());
}
for (int i = 0; i < l.size(); i++) {
sum = sum+l.get(i);
}
avg = sum/(l.size());
System.out.println("Average : " + avg);
Note:
}
} Press Ctrl+Z to stop scanning.
Input with DataInputStream : Calculator Program
import java.io.*;
class InterestCalculator{
public static void main(String args[ ] ) {
Float principalAmount = new Float(0);
Float rateOfInterest = new Float(0);
int numberOfYears = 0;
DataInputStream in = new DataInputStream(System.in);
String tempString;
System.out.println("Enter Principal Amount: ");
System.out.flush();
tempString = in.readLine();
principalAmount = Float.valueOf(tempString);
System.out.println("Enter Rate of Interest: ");
System.out.flush();
tempString = in.readLine();
rateOfInterest = Float.valueOf(tempString);
System.out.println("Enter Number of Years: ");
System.out.flush();
tempString = in.readLine();
numberOfYears = Integer.parseInt(tempString);
// Input is over: calculate the interest
float interestTotal = principalAmount*rateOfInterest*numberOfYears;
System.out.println("Total Interest = " + interestTotal);
}
}
Question to think…