17
Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Course Laboratory Course Lab 3-1: Lab 3-1: Creating and Using Interfaces Creating and Using Interfaces Exception Exception Faculty of Engineering & IT Software Engineering Department WWW.PALINFONET.COM Eng.Omar Al-Nahal

Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Embed Size (px)

Citation preview

Page 1: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Laboratory

Course Course

Lab 3-1:Lab 3-1:Creating and Using Interfaces Creating and Using Interfaces

ExceptionException

Faculty of Engineering & ITSoftware Engineering Department

WWW.PALINFONET.COMWWW.PALINFONET.COM

Eng.Omar Al-Nahal

Eng.Omar Al-Nahal

Page 2: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

What is interface? What is interface?

Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant.

An interface cannot implement any methods, whereas an abstract class can. A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy. Unrelated classes can

implement the same interface

Definition: An interface is a collection of method definitions (without implementations) and constant values.

Page 3: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Defining an Interface Defining an Interface

To create an interfaceTo create an interface, you must write both the interface , you must write both the interface declaration and the interface body.declaration and the interface body.

- interfaceDeclaration- interfaceDeclaration { { interfaceBodyinterfaceBody } }

The interfaceDeclarationThe interfaceDeclaration declares declares various attributes about the various attributes about the interface such as its name and whether it extends another interface. interface such as its name and whether it extends another interface.

The The interfaceBodyinterfaceBody contains the constant and method declarations contains the constant and method declarations within the interface. within the interface.

The Interface Declaration:The Interface Declaration: At minimum, the interface declaration contains the Java keyword At minimum, the interface declaration contains the Java keyword

interface and the name of the interface that you are creating: interface and the name of the interface that you are creating: interface Countable {interface Countable { . . . }. . . } interface declaration looks like this: interface declaration looks like this: [public] interface [public] interface InterfaceNameInterfaceName [extends [extends listOfSuperInterfaceslistOfSuperInterfaces] { . . . } ] { . . . }

Page 4: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Using an Interface Using an Interface

- - An interface gets used when a class claims to implement that An interface gets used when a class claims to implement that interface. A class declares all of the interfaces that it implements in its interface. A class declares all of the interfaces that it implements in its class declaration. class declaration.

- To declare that your class implements one or more interfaces, use the - To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the keyword implements followed by a comma-delimited list of the interfaces implemented by your class. interfaces implemented by your class.

- The FIFOQueue class would declare that it implements the Countable - The FIFOQueue class would declare that it implements the Countable interface like this :interface like this :

class FIFOQueue implements Countable { . . . }

Page 5: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Interfaces Do Not Provide Multiple Interfaces Do Not Provide Multiple InheritanceInheritance

Interfaces are different from multiple inheritance in:Interfaces are different from multiple inheritance in:• you cannot inherit variables from an interface you cannot inherit variables from an interface • you cannot inherit method implementations from you cannot inherit method implementations from

an interface. an interface. • the interface hierarchy is independent of a the the interface hierarchy is independent of a the

class hierarchy--classes that implement the same class hierarchy--classes that implement the same interface may or may not be related through the interface may or may not be related through the class hierarchy. class hierarchy. This is not true for multiple This is not true for multiple inheritanceinheritance..

Page 6: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Interface Example 1Interface Example 1

interface Shape { float area(); }

class Circle implements Shape{ private float r; public Circle(float r){ this.r = r; } public float area(){ return (float) (Math.PI * r * r); } }

class Rectangle implements Shape { private float l, w; public Rectangle(float l, float w){ this.l = l; this.w = w; }

Page 7: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Interface ExamplesInterface Examples

public float area(){ return l*w; } }

class Example1 { public static void main(String args[]){ Shape s[] = new Shape[3]; s[0] = new Circle(7.5f); s[1] = new Rectangle(10,3.5f); s[2] = new Circle(9);

for (int i = 0;i < 3;i++) System.out.println(s[i].area()); } }

Page 8: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Interface Example 2Interface Example 2

interface MySubject {interface MySubject { int arabic = 1;int arabic = 1; int english = 2;int english = 2; int physics = 3;int physics = 3;

}} class One implements MySubject{class One implements MySubject{ public static void main(String args[]){public static void main(String args[]){ System.out.println(arabic);System.out.println(arabic); }} }} class Two {class Two { public static void main(String args[]){public static void main(String args[]){ System.out.println(MySubject.english);System.out.println(MySubject.english); }} }}

Page 9: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Exception Handling OverviewException Handling Overview

KeywordsKeywords• TryTry

– Include codes in which exceptions might occurInclude codes in which exceptions might occur

• CatchCatch– Represent types of exceptions the catch can handleRepresent types of exceptions the catch can handle

• Finally Finally – (Optional) codes present here will always execute(Optional) codes present here will always execute

Exception handlingException handling• Process synchronous errorsProcess synchronous errors

• Follows the termination model of exception handlingFollows the termination model of exception handling

Page 10: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

try-catchtry-catch Syntax Syntax

try try {{ <try block><try block>}}catchcatch ( <ExceptionClass> <name> ) ( <ExceptionClass> <name> ) {{ <catch block><catch block>}}catchcatch ( <ExceptionClass> <name> ) ( <ExceptionClass> <name> ) {{ <catch block><catch block>}…}…

Page 11: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Example: DivideByZeroExceptionExample: DivideByZeroException

Error catchingError catching• Method Convert.ToInt32 will automatically detect for invalid Method Convert.ToInt32 will automatically detect for invalid

representation of an integerrepresentation of an integer– Method generates a FormatExceptionMethod generates a FormatException

• CLR automatic detection for division by zeroCLR automatic detection for division by zero– Occurrence will cause a DivideByZeroExceptionOccurrence will cause a DivideByZeroException

// Fig. 13.1: DivideByZeroNoExceptionHandling.java import java.util.Scanner; public class ex01 { // demonstrates throwing an exception when a divide-by-zero occurs public static int quotient( int numerator, int denominator ) { return numerator / denominator; // possible division by zero } // end method quotient

public static void main( String args[] ) {

Page 12: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Example: DivideByZeroExceptionExample: DivideByZeroException

Scanner scanner = new Scanner( System.in ); // scanner for input

System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt();

int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); } // end main } // end class DivideByZeroNoExceptionHandling

Please enter an integer numerator: 100

Please enter an integer denominator: 0

Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoException- Handling.java:10) at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHan- dling. java:22)

Out

put:

Ple

ase

ente

r an

inte

ger

num

erat

or: 1

00P

leas

e en

ter

an in

tege

r de

nom

inat

or: 7

Res

ult:

100

/ 7

= 1

4

Page 13: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Throwing ExceptionsThrowing Exceptions

Page 14: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

Finally clauseFinally clause

What if there is some code we want to execute regardless of What if there is some code we want to execute regardless of exception or not?exception or not?• finally finally block is usedblock is used

try{distance = Double.parseDouble(str);if (distance < 0){

throw new Exception("Negative distance is not valid"); } return distance;

} catch (NumberFormatException e){System.out.println("'" + str + "'not valid

input, Please use digits only");} catch (Exception e){

System.out.println(e.getMessage());} finally { System.out.println(“Done”); }

Page 15: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

try-catchtry-catch Control Flow Control Flow

code before try

try block

code after try

no exceptions occur

code before try

try block catch blockexception occurs

code after try

Page 16: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

try-catchtry-catch Control Flow Control Flow

try blockexception occurs

code after try

code before try

finally block (if it exists)

catch block

Page 17: Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering

ExampleExampleclass Example1{

public static void f(int x) throws Exception{if (x<0)

throw new Exception("NegativeNotAllowedException");//else

System.out.println(" X is "+x); }public static void main(String args[]){

try {f(4);

}catch(Exception e){ System.out.println(e);}finally{} } }

class One {public static void main(String args[]){

int x=4, m, y=0;try {

m = x/y;}catch(ArithmeticException e){

System.out.println(e); }

int a[] = {4,5,6,7};try {

a[8] = 10;}catch(ArrayIndexOutOfBoundsException e){

System.out.println(e); } } }