Download presentation
Presentation is loading. Please wait.
Published byShawn Blair Modified over 9 years ago
1
Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering Department WWW.PALINFONET.COM Eng.Omar Al-Nahal Eng.Omar Al-Nahal
2
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. b b An interface cannot implement any methods, whereas an abstract class can. b b A class can implement many interfaces but can have only one superclass. b b 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.
3
Defining an Interface b To create an interface, you must write both the interface declaration and the interface body. - interfaceDeclaration { interfaceBody } - interfaceDeclaration { interfaceBody } The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface. The interfaceBody contains the constant and method declarations within the interface. b The Interface Declaration: At minimum, the interface declaration contains the Java keyword interface and the name of the interface that you are creating: At minimum, the interface declaration contains the Java keyword interface and the name of the interface that you are creating: interface Countable { interface Countable {... }... } b interface declaration looks like this: [public] interface InterfaceName [extends listOfSuperInterfaces] {... } [public] interface InterfaceName [extends listOfSuperInterfaces] {... }
4
Using an Interface - An interface gets used when a class claims to implement that interface. A class declares all of the interfaces that it implements in its class declaration. - An interface gets used when a class claims to implement that interface. A class declares all of the interfaces that it implements in its class declaration. - To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the interfaces implemented by your class. - To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the interfaces implemented by your class. - The FIFOQueue class would declare that it implements the Countable interface like this : - The FIFOQueue class would declare that it implements the Countable interface like this : class FIFOQueue implements Countable {... }
5
Interfaces Do Not Provide Multiple Inheritance Interfaces are different from multiple inheritance in: you cannot inherit variables from an interfaceyou cannot inherit variables from an interface you cannot inherit method implementations from an interface.you cannot inherit method implementations from an interface. the interface hierarchy is independent of a the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance.the interface hierarchy is independent of a the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance.
6
Interface Example 1 b b interface Shape { b b float area(); bb}bb} b b class Circle implements Shape{ b b private float r; b b public Circle(float r){ b b this.r = r; bb}bb} b b public float area(){ b b return (float) (Math.PI * r * r); bb}bb} bb}bb} b b class Rectangle implements Shape { b b private float l, w; b b public Rectangle(float l, float w){ b b this.l = l; b b this.w = w; bb}bb}b
7
Interface Examples b b public float area(){ b b return l*w; bb}bb} bb}bb} b b class Example1 { b b public static void main(String args[]){ b b Shape s[] = new Shape[3]; b b s[0] = new Circle(7.5f); b b s[1] = new Rectangle(10,3.5f); b b s[2] = new Circle(9);b b b for (int i = 0;i < 3;i++) b b System.out.println(s[i].area()); bb}bb} bb}bb}
8
Interface Example 2 b interface MySubject { b int arabic = 1; b int english = 2; b int physics = 3; b b}b}b}b} b class One implements MySubject{ b public static void main(String args[]){ b System.out.println(arabic); b}b}b}b} b}b}b}b} b class Two { b public static void main(String args[]){ b System.out.println(MySubject.english); b}b}b}b} b}b}b}b}
9
Exception Handling Overview b Keywords TryTry –Include codes in which exceptions might occur CatchCatch –Represent types of exceptions the catch can handle FinallyFinally –(Optional) codes present here will always execute b Exception handling Process synchronous errorsProcess synchronous errors Follows the termination model of exception handlingFollows the termination model of exception handling
10
try-catch Syntax try{ } catch ( ) { } catch ( ) { }…
11
Example: DivideByZeroException b Error catching Method Convert.ToInt32 will automatically detect for invalid representation of an integerMethod Convert.ToInt32 will automatically detect for invalid representation of an integer –Method generates a FormatException CLR automatic detection for division by zeroCLR automatic detection for division by zero –Occurrence 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[] ) {
12
Example: 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) Output: Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14
13
Throwing Exceptions
14
Finally clause b What if there is some code we want to execute regardless of exception or not? finally block is usedfinally block 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”); }
15
try-catch Control Flow code before try try block code after try no exceptions occur code before try try block catch block exception occurs code after try
16
try-catch Control Flow try block exception occurs code after try code before tryfinally block (if it exists)catch block
17
Example class 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); }} }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.