Computer Science 538 Lecture Notes for 5-3-00 Lecture by Professor Fischer Notes by Michael Waddell "Advanced" JAVA --------------- I. Interfaces II. Exceptions III. Threads I. Interfaces ------------- Java only has single inheritance - not multiple inheritance. BUT, it allows multiple interfaces. Interface Compare { Boolean LessThan(Object O1, Object O2); } Interfaces are just classes that lack implementation. You implement them in other classes. Class IntCompare Implements Compare { Boolean LessThan(Object i1, Object i2) { return ((Integer)i1).intVal() < ((Integer)i2).intVal(); } ... } Class StringCompare Implements Compare { Boolean LessThan(Object s1, Object s2) { return ((String)s1).compareTo((String)s2) < 0; } ... } Class PrintCompare { static void printAns(Object v1, Object v2, Compare c) { System.out.println(v1 + "<" + v2 + "is" + c.LessThan(v1,v2); } } PrintCompare.printAns("abc", "xyz", new StringCompare); II. Exceptions -------------- All exceptions are subclasses of Throwable. Throwable / \ Exception Error / RunTimeException Exceptions use a Try/Catch block syntax: Try { ... Throw new Exception(); ... } Catch(Exception) {System.out.println("Exception Caught!"); } Exceptions come in 2 types: Checked - you can't ignore this kind Unchecked - you can ignore them if you want, but they will terminate the program if uncaught III. Threads ------------ Java supports multi-threading This is very useful for GUIs, etc. To use threading, you need a "Runnable" class. Interface Runnable { public void run(); } Class PingPong implements Runnable{ int delay; String word; PingPong(...) {...} public void run() { try {while(true) {System.out.println(word + " "); Thread.sleep(delay); } catch(interruptedExecution e) {} } public static void main(string args[]) { thread t1 = new thread(new PingPong(33,"ping"); thread t2 = new thread(new PingPong(100,"pong"); t1.start(); t2.start(); } } output: ping pong ping ping ping pong ping ping ping pong ... Notice that although PingPong.run() seems like it would run forever, you can throw an exception at it that causes it to gracefully exit. Continued on Friday...