Upload
others
View
8
Download
0
Embed Size (px)
Citation preview
§ A Java interface is composed of a collection of abstract methods and constants
public interface Doable { public void doThis(); public int doThat(int num); public boolean doTheOther (); }
None of the methods in an interface are given
a definition (body)
A semicolon immediately follows each method header
Sinceallmethodsinaninterfaceareabstract,thekeywordabstract isleftoff
§ Why may an interface not be instantiated?
§ Why are interface methods public by default?
§ Why must a class implementing an interface define all methods in the interface?
§ Why may a class implementing an interface also implement other methods?
F- 3
public class CanDo implements Doable { public void doThis () { // code to do this } public void doThat (int num) { // code to do that } public boolean doTheOther () { // whatever } }
implements and interface are reserved words
Each method listed
in Doable
is given a
definition
F- 4
F- 5 F- 6
F- 7
§ A class can implement multiple interfaces
§ The interfaces are listed in the implements clause
§ The class must implement all methods in all interfaces listed in the header
F- 8
class Horse implements Mammal, Toy {
// all methods of both interfaces
}
Mammal
Horse
Toy
§ The Java standard class library has many helpful interfaces
§ The Comparable interface contains one abstract method called compareTo, which is used to compare two objects
§ The String class implements Comparable, giving us the ability to put strings in lexicographic order
F- 9
Comparable
String
§ Any class can implement Comparable to provide a mechanism for comparing objects of that type
F- 10
if (obj1.compareTo(obj2) < 0)
System.out.println ("obj1 is less than obj2");
• It’s up to the programmer to determine what makes one object < than another
• You may define the compareTo method of an Employee class to order employees by name (alphabetically) or by employee number
• The implementation of the method can be as straightforward or as complex as needed for the situation
§ The String class contains a method called compareTo to determine if one string comes before another
§ A call to name1.compareTo(name2)
§ returns zero if name1 and name2 are equal (contain the same characters)
§ returns a negative value if name1 is less than name2
§ returns a positive value if name1 is greater than name2
A-1 11
if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first");
§ An iterator is an object that provides a means of processing a collection of objects, one at a time
§ It is created formally by implementing the Iterator interface’s 3 methods § The hasNext method returns a boolean – true if there are items left to process § The next method returns the next object in the iteration § The remove method removes the object most recently returned by the next
method
§ By implementing the Iterator interface, a class formally establishes that objects of that type are iterators
§ Once established, the for-each version of the for loop can be used to process the items in the iterator
F- 12
Scanner
Iterator
§ An interface name can be used as the type of an object reference variable
Speaker current;
§ The current reference can be used to point to any object of any class that implements the Speaker interface
§ The version of speak that the following line invokes depends on the type of object that current is referencing
current.speak();
F- 13
<<interface>>Speaker
Philosopher
+speak()
§ Suppose two classes, Philosopher and Politician, both implement the Speaker interface, providing distinct versions of the speak method
§ In the following code, the first call to speak invokes one version and the second invokes another
Speaker guest = new Philospher(); guest.speak(); guest = new Politician(); guest.speak();
F- 14
<<interface>> Speaker
Politician
+speak()
Philosopher
+speak()
§ Create an interface called Streaming that has methods that represent the standard operations of a streaming video player (play, stop, etc.).
§ Define method signatures in any reasonable way.
§ How might a class, say Netflix, implement the interface?
§ An exception is an object describing unusual or erroneous situation
§ Division by 0 in computing expression (ArithmeticException)
§ Array index out of bounds (IndexOutOfBoundsException)
§ Null pointer cannot be followed (NullPointerException)
§ I/O problems (e.g., no space on disk to save file, file not found) (IOException)
§ No permissions to do something (e.g., to save a file) (FileNotFoundException)
§ Exceptions are thrown by a program, and may be caught and handled by another part of the program
§ (An error is also an object, but it represents a unrecoverable situation and should not be caught)
§ To handle an exception, the line that throws the exception is executed within a try block
§ A try block is followed by one or more catch clauses
§ When an exception occurs, processing continues at the first catch clause that matches the exception type
1-18
// here is code that // should generate no exceptionstry {
// code to monitor // several possible things // that can go wrong// goes here
} catch (ExceptionTypeA ex) {
//handler for ExceptionTypeA } catch (ExceptionTypeB ex) {
//handler for ExceptionTypeB } // after a catch, continue here
try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); }
// Counts the number of product codes that are entered // with a zone of R and district greater than 2000.
D I S T Z
The throws clause
modifiers r_type methodName(p_type param, …) throws e_type { … }
§ A checked exception requires explicit handling. It must
§ be caught by a method, (using try-catch block)
or
§ be asserted in the throws clause of any method that may throw or propagate it
§ The compiler will issue error if a checked exception is not caught or asserted in a throws clause 1-22
• An unchecked exception does not require explicit handling
• One type of unchecked exceptions in Java are objects of type RuntimeException (or any of its descendants)
• Another type are Errors
• They represent conditions which are Really Bad: “serious problems that a reasonable application should not try to catch.”
• Examples: “OutOfMemoryError and StackOverflowError
/* Read in the contents of a file line by line, * and print out each line after it is read in.
* Stop when the end of the file is reached.
*/
public static void displayFile (String inFileName) {
try { Scanner fileScan = new Scanner (new File(inFileName));
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
}
} catch (IOException ex) {
System.out.println(ex);
} }
/* Read in the contents of a web page line by line,
* and print out each line after it is read in.
* Stop when the end of the web page is reached.
*/
public static void displayWebPage (String urlName) {
try {
URL u = new URL(urlName);
// will throw exception
Scanner urlScan = new Scanner( u.openStream() );
while (urlScan.hasNext()) {
String line = urlScan.nextLine();
System.out.println(line);
}
} catch (IOException ex) {
System.out.println(ex);
}
}
/* Read in lines of text from the keyboard,
* and print out each line after it is read in.
* Stop when the user hits CONTROL-D.
*/
public static void displayKeyboardInput () {
// will not throw
Scanner keyboardScan = new Scanner (System.in);
do {
String line = keyboardScan.nextLine();
System.out.println(line);
} while (keyboardScan.hasNext());
}
/* Copies an input file to an output file. Displays an error message if the output file cannot be created.
*/ public static void copyFile(String inFileName,
String outFileName){ try{ Scanner reader = new Scanner (new File(inFileName)); PrintWriter writer = new PrintWriter (new File(outFileName)); while (reader.hasNext()) { // Read and write line to output file writer.println(reader.nextLine()); } }catch (IOException ex) { System.out.println(ex); // Handle file-not-found } }
/* * Reads in a files and stores the contents in a String. This method is * inefficient because it uses a String concatenation rather than a * StringBuilder to collect the lines of the files */ public static String fileToString_inefficient (String inFileName) {
try { Scanner reader = new Scanner(new File(inFileName)); String linesFromFile = ""; //Var for accumulating String from file while (reader.hasNext()) { //Continue until reach end of input file linesFromFile = linesFromFile + reader.nextLine() + "\n";
//nextLine() omits the newline character, so add back in } reader.close(); // Close the file reader return linesFromFile;
} catch (FileNotFoundException ex) { System.out.println(ex); // Handle FNF by displaying message
return ""; // Return the empty string if file not found } }
/* Reads in a file and stores the contents in a StringBuffer. * This method is more efficient because it uses a * StringBuilder rather than String concatenation to collect * the lines of the files. */ public static String fileToString (String inFileName) { try { Scanner reader = new Scanner(new File(inFileName)); //Accumulate lines in StringBuilder
StringBuilder builder = new StringBuilder(); while (reader.hasNext()) { // Continue until EOF builder.append(reader.nextLine()); builder.append(“\n”); // nextLine() omits newline, re-add } reader.close(); // Close the file reader return builder.toString(); } catch (FileNotFoundException ex) { System.out.println(ex); // Handle FNF by displaying message return ""; // Return the empty string if file not found } }
Write a method that takes the name of a file as input and prints out the number of characters in the file and the number of lines in the file.