Java Exception Handling errors using Javas exception handling

  • Slides: 107
Download presentation
Java Exception Handling errors using Java’s exception handling mechanism James Tam

Java Exception Handling errors using Java’s exception handling mechanism James Tam

Approaches For Dealing With Error Conditions • Use branches/decision making and return values •

Approaches For Dealing With Error Conditions • Use branches/decision making and return values • Use Java’s exception handling mechanism James Tam

Class Inventory: An Earlier Example public class Inventory { public final int MIN =

Class Inventory: An Earlier Example public class Inventory { public final int MIN = 0; public final int MAX = 100; public final int CRITICAL = 10; public boolean add(int amount) { int temp; temp = stock. Level + amount; if (temp > MAX) { System. out. print("Adding " + amount + " item will cause stock "); System. out. println("to become greater than " + MAX + " units (overstock)"); return(false); } James Tam

Class Inventory: An Earlier Example (2) else { stock. Level = stock. Level +

Class Inventory: An Earlier Example (2) else { stock. Level = stock. Level + amount; return(true); } } // End of method add(). . . James Tam

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2()

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2() == false) return(false); reference 2. method 2() if (store. add. To. Inventory(amt) == false) return(false); store. add. To. Inventory(int amt) if (temp > MAX) return(false); James Tam

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() Problem 1: The calling method

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() Problem 1: The calling method may forget to check the return value if (reference 2. method 2() == false) return(false); reference 2. method 2() if (store. add. To. Inventory(amt) == false) return(false); store. add. To. Inventory(int amt) if (temp > MAX) return(false); James Tam

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2()

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2() == false) return(false); reference 2. method 2() if (store. add. To. Inventory(amt) == false) return(false); Problem 2: A long series of method calls requires many checks/returns store. add. To. Inventory(int amt) if (temp > MAX) return(false); James Tam

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2()

Some Hypothetical Method Calls: Condition/Return reference 1. method 1() if (reference 2. method 2() == false) return(false); reference 2. method 2() if (store. add. To. Inventory(amt) == false) ? ? return(false); ? ? Problem 3: The calling method may not know how to handle the error store. add. To. Inventory(int amt) if (temp > MAX) return(false); James Tam

Approaches For Dealing With Error Conditions • Use branches/decision making constructs and return values

Approaches For Dealing With Error Conditions • Use branches/decision making constructs and return values • Use Java’s exception handling mechanism James Tam

Handling Exceptions Format: try { // Code that may cause an error/exception to occur

Handling Exceptions Format: try { // Code that may cause an error/exception to occur } catch (Exception. Type identifier) { // Code to handle the exception } James Tam

Handling Exceptions: Reading Input Location of the online example: /home/219/examples/exceptions/handling. Exceptions/input. Example public class

Handling Exceptions: Reading Input Location of the online example: /home/219/examples/exceptions/handling. Exceptions/input. Example public class Driver { public static void main(String [] args) { Buffered. Reader string. Input; Input. Stream. Reader character. Input; String s; int num; character. Input = new Input. Stream. Reader(System. in); string. Input = new Buffered. Reader(character. Input); James Tam

Handling Exceptions: Reading Input (2) try { System. out. print("Type an integer: "); s

Handling Exceptions: Reading Input (2) try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int(s); System. out. println("Converted to an integer. . . " + num); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) {. . . } } } James Tam

Handling Exceptions: Where The Exceptions Occur The first exception can occur here try {

Handling Exceptions: Where The Exceptions Occur The first exception can occur here try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int(s); System. out. println("Converted to an integer. . . " + num); } James Tam

Handling Exceptions: Result Of Calling Buffered. Reader. Read. Line() try { System. out. print("Type

Handling Exceptions: Result Of Calling Buffered. Reader. Read. Line() try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int(s); System. out. println("Converted to an integer. . . " + num); } James Tam

Where The Exceptions Occur In Class Buffered. Reader • For online documentation for this

Where The Exceptions Occur In Class Buffered. Reader • For online documentation for this class go to: - http: //docs. oracle. com/javase/7/docs/api/java/io/Buffered. Reader. htm l public class Buffered. Reader { public Buffered. Reader(Reader in); public Buffered. Reader(Reader in, int sz); public String read. Line() throws IOException; . . . } James Tam

Handling Exceptions: Result Of Calling Integer. Parse. Int () try { The second exception

Handling Exceptions: Result Of Calling Integer. Parse. Int () try { The second exception can occur here System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int(s); System. out. println("Converted to an integer. . . " + num); } James Tam

Where The Exceptions Occur In Class Integer • For online documentation for this class

Where The Exceptions Occur In Class Integer • For online documentation for this class go to: - http: //docs. oracle. com/javase/7/docs/api/java/lang/Integer. html public class Integer { public Integer(int value); public Integer(String s) throws Number. Format. Exception; . . . public static int parse. Int(String s) throws Number. Format. Exception; . . . } James Tam

Handling Exceptions: The Details try { System. out. print("Type an integer: "); s =

Handling Exceptions: The Details try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int(s); System. out. println("Converted to an integer. . . " + num); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) {. . . } } } James Tam

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Driver. main () try

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Driver. main () try } { num = Integer. parse. Int(s); } : catch (Number. Format. Exception e) { : } James Tam

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Oops! The user didn’t

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Oops! The user didn’t enter an integer Driver. main () try } { num = Integer. parse. Int(s); } : catch (Number. Format. Exception e) { : } James Tam

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e = new Number. Format. Exception (); Driver. main () try } { num = Integer. parse. Int(s); } : catch (Number. Format. Exception e) { : } James Tam

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e = new Number. Format. Exception (); Driver. main () try } { num = Integer. parse. Int(s); } : catch (Number. Format. Exception e) { : } James Tam

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e

Handling Exceptions: Tracing The Example Integer. parse. Int(String s) { Number. Format. Exception e = new Number. Format. Exception (); Driver. main () try } { num = Integer. parse. Int(s); } : catch (Number. Format. Exception e) { } Exception must be dealt with here James Tam

Handling Exceptions: Catching The Exception catch (Number. Format. Exception e) {. . . }

Handling Exceptions: Catching The Exception catch (Number. Format. Exception e) {. . . } } } James Tam

Catching The Exception: Error Messages catch (Number. Format. Exception e) { System. out. println("You

Catching The Exception: Error Messages catch (Number. Format. Exception e) { System. out. println("You entered a non-integer value. "); System. out. println(e. get. Message()); System. out. println(e); e. print. Stack. Trace(); } } } James Tam

Catching The Exception: Error Messages catch (Number. Format. Exception e) For input string: "james

Catching The Exception: Error Messages catch (Number. Format. Exception e) For input string: "james tam" { System. out. println("You entered a non-integer value. "); System. out. println(e. get. Message()); System. out. println(e); e. print. Stack. Trace(); } java. lang. Number. Format. Exceptio For input string: "james tam" } } java. lang. Number. Format. Exception: For input string: "james tam" at java. lang. Number. Format. Exception. for. Input. String(Number. Format. Exception. java: 48) at java. lang. Integer. parse. Int(Integer. java: 426) at java. lang. Integer. parse. Int(Integer. java: 476) at Driver. main(Driver. java: 39) James Tam

Avoid Squelching Your Exceptions try { s = string. Input. read. Line(); num =

Avoid Squelching Your Exceptions try { s = string. Input. read. Line(); num = Integer. parse. Int(s); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { // Do nothing here but set up the try-catch block to // bypass the “annoying” compiler error } James Tam

Avoid Squelching Your Exceptions try { s = string. Input. read. Line(); num =

Avoid Squelching Your Exceptions try { s = string. Input. read. Line(); num = Integer. parse. Int(s); NO! } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { // Do nothing here but set up the try-catch block to // bypass the “annoying” compiler error } James Tam

The Finally Clause • An additional part of Java’s exception handling model (trycatch-finally). •

The Finally Clause • An additional part of Java’s exception handling model (trycatch-finally). • Used to enclose statements that must always be executed whether or not an exception occurs. James Tam

The Finally Clause: Exception Thrown f. method () { try { f. method(); }

The Finally Clause: Exception Thrown f. method () { try { f. method(); } } catch { } finally { } James Tam

The Finally Clause: Exception Thrown f. method () te the at u c e

The Finally Clause: Exception Thrown f. method () te the at u c e x pt to e try block th m e t t A 1) in the ception d o h t me n ex a w o r may th try { f. method(); { 2) Exception thrown here } } catch { is n o pti ere e c x th 3) E augh c } finally 4) A the end of the catch block control transfers to the finally clause { } James Tam

The Finally Clause: No Exception Thrown f. method () try { f. method(); ecute

The Finally Clause: No Exception Thrown f. method () try { f. method(); ecute x e o t mpt e 1) Atte ethod in th y the m at ma h t k c ption try blo e c x e an throw { 2) Code runs okay here } } catch { } () lly od fina h t me the. f f rs to o nd nsfe e a the ol tr A tr 3) con se u cla finally { } James Tam

Try-Catch-Finally: An Example Location of the online example: /home/219/examples/exceptions/handling. Exceptions/try. Catch. Finally. Example public

Try-Catch-Finally: An Example Location of the online example: /home/219/examples/exceptions/handling. Exceptions/try. Catch. Finally. Example public class Driver { public static void main(String [] args) { TCFExample eg = new TCFExample(); eg. method(); } } James Tam

Try-Catch-Finally: An Example (2) public class TCFExample { public void method() { Buffered. Reader

Try-Catch-Finally: An Example (2) public class TCFExample { public void method() { Buffered. Reader br; String s; int num; try { System. out. print("Type in an integer: "); br = new Buffered. Reader(new Input. Stream. Reader(System. in)); s = br. read. Line(); num = Integer. parse. Int(s); return; } James Tam

Try-Catch-Finally: An Example (3) catch (IOException e) { e. print. Stack. Trace(); return(); }

Try-Catch-Finally: An Example (3) catch (IOException e) { e. print. Stack. Trace(); return(); } catch (Number. Format. Exception e) { e. print. Stack. Trace(); return(); } finally { System. out. println("<<<This code will always execute>>>"); return; } } } James Tam

When The Caller Can’t Handle The Exceptions method 2 () Exception thrown! method 1

When The Caller Can’t Handle The Exceptions method 2 () Exception thrown! method 1 () ? ? ? main () James Tam

When The Caller Can’t Handle The Exceptions: An Example Location of the online example:

When The Caller Can’t Handle The Exceptions: An Example Location of the online example: /home/219/examples/exceptions/handling. Exceptions/delegating. Exceptions James Tam

When The Caller Can’t Handle The Exceptions: An Example (2) • Tracing the method

When The Caller Can’t Handle The Exceptions: An Example (2) • Tracing the method calls when no exception occurs: Driver. main() TCFExample. method() Buffered. Reader. read. Line() Integer. parse. Int() User enters 10 Break out of loop Yes indeed it is an integer! James Tam

When The Caller Can’t Handle The Exceptions: An Example (3) • Tracing the method

When The Caller Can’t Handle The Exceptions: An Example (3) • Tracing the method calls when an exception does occur: Driver. main() TCFExample. method() Buffered. Reader. read. Line() Integer. parse. Int() User enters 1. 9 Return to the top of loop and start the calls again This string is not an integer. James Tam

When The Caller Can’t Handle The Exceptions: An Example (4) public class Driver {

When The Caller Can’t Handle The Exceptions: An Example (4) public class Driver { public static void main(String [] args) { TCExample eg = new TCExample(); boolean input. Okay = true; James Tam

When The Caller Can’t Handle The Exceptions: An Example (5) do { } }

When The Caller Can’t Handle The Exceptions: An Example (5) do { } } try { eg. method(); input. Okay = true; } catch (IOException e) { e. print. Stack. Trace(); } catch (Number. Format. Exception e) { input. Okay = false; System. out. println("Please enter a whole number. "); } } while(input. Okay == false); // End of main // End of Driver class James Tam

When The Caller Can’t Handle The Exceptions: An Example (6) public class TCExample {

When The Caller Can’t Handle The Exceptions: An Example (6) public class TCExample { public void method() throws IOException, Number. Format. Exception { Buffered. Reader br; String s; int num; System. out. print("Type in an integer: "); br = new Buffered. Reader(new Input. Stream. Reader(System. in)); s = br. read. Line(); num = Integer. parse. Int(s); } } James Tam

When The Driver. Main() Method Can’t Handle The Exception public class Driver { public

When The Driver. Main() Method Can’t Handle The Exception public class Driver { public static void main(String [] args) throws IOException, Number. Format. Exception { TCExample eg = new TCExample (); eg. method(); } } James Tam

Creating Your Own Exceptions (If There Is Time) Throwable Error Virtual. Machine. Error Exception

Creating Your Own Exceptions (If There Is Time) Throwable Error Virtual. Machine. Error Exception . . . IOException . . . ? ? ? Run. Time Exception Out. Of. Memory. Error Excerpt from Big Java by C. Horstmann p. 562 James Tam

Class Exception: The Local Inheritance Hierarchy Exception Class. Not. Found IOException Clone. Not. Found

Class Exception: The Local Inheritance Hierarchy Exception Class. Not. Found IOException Clone. Not. Found Exception EOFException File. Not. Found Malformed. URL Unknown. Host Exception James Tam

Writing New Exceptions • Typical approach: tie the exception into preconditions • Remember: preconditions

Writing New Exceptions • Typical approach: tie the exception into preconditions • Remember: preconditions are things that must be true when a function is called. Pre-condition: • Example: Inventory example Existing inventory and new amount don’t exceed MAX Arg: amount add. To. Inventory( ) If (precondition not met) then Exception occurs Else add amount to inventory James Tam

Writing New Exceptions (2) • Example 2: Division Quotient = dividend/divisor Args: dividend, divisor

Writing New Exceptions (2) • Example 2: Division Quotient = dividend/divisor Args: dividend, divisor division( ) Pre-condition: divisor not zero If (precondition not met) then Exception occurs Else Perform division James Tam

Writing New Exceptions: An Example Location of the online example: /home/219/examples/exceptions/writing. Exceptions/inventory. Example James

Writing New Exceptions: An Example Location of the online example: /home/219/examples/exceptions/writing. Exceptions/inventory. Example James Tam

Writing New Exceptions: Driver Class public class Driver { public static void main(String []

Writing New Exceptions: Driver Class public class Driver { public static void main(String [] args) { Inventory chinook = new Inventory(); try { chinook. add(10); } catch (Inventory. Over. Max. Exception e) { System. out. print(">>Too much to be added to stock<<"); } James Tam

Writing New Exceptions: Driver Class (2) System. out. println(chinook. show. Stock. Level()); try {

Writing New Exceptions: Driver Class (2) System. out. println(chinook. show. Stock. Level()); try { chinook. add(10); } catch (Inventory. Over. Max. Exception e) { System. out. println(">>Too much to be added to stock<<"); } James Tam

Writing New Exceptions: Driver Class (3) System. out. println(chinook. show. Stock. Level()); try {

Writing New Exceptions: Driver Class (3) System. out. println(chinook. show. Stock. Level()); try { chinook. add(100); } catch (Inventory. Over. Max. Exception e) { System. out. println(">>Too much to be added to stock<<"); } James Tam

Writing New Exceptions: Driver Class (4) System. out. println(chinook. show. Stock. Level()); try {

Writing New Exceptions: Driver Class (4) System. out. println(chinook. show. Stock. Level()); try { chinook. remove(21); } catch (Inventory. Under. Min. Exception e) { System. out. println(">>Too much to remove from stock<<"); } System. out. println(chinook. show. Stock. Level()); } } James Tam

Writing New Exceptions: Class Inventory public class Inventory { public final int CRITICAL =

Writing New Exceptions: Class Inventory public class Inventory { public final int CRITICAL = 10; public final int MIN = 0; public final int MAX = 100; private int stock. Level = 0; public boolean inventory. Too. Low() { if (stock. Level < CRITICAL) return(true); else return(false); } James Tam

Writing New Exceptions: Class Inventory (2) public void add(int amount) throws Inventory. Over. Max.

Writing New Exceptions: Class Inventory (2) public void add(int amount) throws Inventory. Over. Max. Exception { int temp; temp = stock. Level + amount; if (temp > MAX) “Throws”: • An exception of type <E> can occur in this method { throw new Inventory. Over. Max. Exception("Adding " + amount + " item(s) "+ "will cause stock to become greater than " + MAX + " units"); } else } “Throw”: • Instantiates an exception of type <E> stock. Level = stock. Level + amount; • Execution transfers back to the ‘catch’ block of the caller James Tam

Writing New Exceptions: Class Inventory (3) public void remove(int amount) throws Inventory. Under. Min.

Writing New Exceptions: Class Inventory (3) public void remove(int amount) throws Inventory. Under. Min. Exception { int temp; temp = stock. Level - amount; if (temp < MIN) { throw new Inventory. Under. Min. Exception("Removing " + amount + " item(s) will cause stock to become less " than " + MIN + " units"); } else stock. Level = temp; } public String show. Stock. Level() { return("Inventory: " + stock. Level); } } James Tam

Writing New Exceptions: Class Inventory. Over. Max. Exception public class Inventory. Over. Max. Exception

Writing New Exceptions: Class Inventory. Over. Max. Exception public class Inventory. Over. Max. Exception extends Exception { public Inventory. Over. Max. Exception() { super(); } public Inventory. Over. Max. Exception(String s) { super(s); } } James Tam

Writing New Exceptions: Class Inventory. Under. Min. Exception public class Inventory. Under. Min. Exception

Writing New Exceptions: Class Inventory. Under. Min. Exception public class Inventory. Under. Min. Exception extends Exception { public Inventory. Under. Min. Exception() { super(); } public Inventory. Under. Min. Exception(String s) { super(s); } } James Tam

Inheritance Hierarchy For IOExceptions IOException These classes are more specific instances of class IOException

Inheritance Hierarchy For IOExceptions IOException These classes are more specific instances of class IOException EOFException File. Not. Found Exception James Tam

Inheritance And Catching Exceptions • If you are catching a sequence of exceptions then

Inheritance And Catching Exceptions • If you are catching a sequence of exceptions then make sure that you catch the exceptions for the child classes before you catch the exceptions for the parent classes • Deal with the more specific case before handling the more general case James Tam

Inheritance And Catching Exceptions (2) Correct Incorrect try { { } } catch (EOFException

Inheritance And Catching Exceptions (2) Correct Incorrect try { { } } catch (EOFException e) catch (IOException e) { { } } catch (IOException e) catch (EOFException e) { { } } James Tam

After This Section You Should Now Know • The benefits of handling errors with

After This Section You Should Now Know • The benefits of handling errors with an exception handler rather than employing a series of return values and conditional statements/branches. • How to handle exceptions - Being able to call a method that may throw an exception by using a trycatch block - What to do if the caller cannot properly handle the exception - What is the finally clause, how does it work and when should it be used • How to write your classes of exceptions • The effect of the inheritance hierarchy when catching exceptions James Tam

Simple File Input And Output You will learn how to write to and read

Simple File Input And Output You will learn how to write to and read from text files in Java. James Tam

Inheritance Hierarchy For IOExceptions IOException These classes are more specific instances of class IOException

Inheritance Hierarchy For IOExceptions IOException These classes are more specific instances of class IOException EOFException File. Not. Found Exception James Tam

Inheritance And Catching Exceptions • If you are catching a sequence of exceptions then

Inheritance And Catching Exceptions • If you are catching a sequence of exceptions then make sure that you catch the exceptions for the child classes before you catch the exceptions for the parent classes • Deal with the more specific case before handling the more general case James Tam

Branches: Specific Before General • Correct if (x > 100) body; else if (x

Branches: Specific Before General • Correct if (x > 100) body; else if (x > 10) body; else if (x > 0) body; • Incorrect if (x > 0) body; else if (x > 100) body; James Tam

Inheritance And Catching Exceptions (2) Correct Incorrect try { { } } catch (EOFException

Inheritance And Catching Exceptions (2) Correct Incorrect try { { } } catch (EOFException e) catch (IOException e) { { } } catch (IOException e) catch (EOFException e) { { } } James Tam

Reading Text Input From A File Buffered. Reader 01000001 am 01000001 File. Reader ‘‘

Reading Text Input From A File Buffered. Reader 01000001 am 01000001 File. Reader ‘‘ am re st : byte ‘N’ 01001110 ar 01000001 ch 01001110 ‘A’ 00100000 “AN “ String James Tam

Writing Text Output To A File Primitives, “AN “ 000 01 Objects 1 01001110

Writing Text Output To A File Primitives, “AN “ 000 01 Objects 1 01001110 01000001 : st re am 01000001 te File. Writer File by am tre rs 00 ‘A’ 10 0 ‘N’ 00 0 ‘‘ cha 1 By objects we of course mean references to objects 01 00 11 10 Print. Writer 010 Strings, James Tam

File Input And Output: One Complete Example Location of the online example: /home/219/examples/file. IO/Driver.

File Input And Output: One Complete Example Location of the online example: /home/219/examples/file. IO/Driver. java public class Driver { final static int MAX = 4; public static void main(String [] args) { String line = null; String [] paragraph = null; int i; Scanner in; // File IO Print. Writer pw = null; File. Writer fw = null; Buffered. Reader br = null; File. Reader fr = null; in = new Scanner(System. in); paragraph = new String[MAX]; James Tam

File IO: Get Data And Write To File // Get paragraph information from the

File IO: Get Data And Write To File // Get paragraph information from the user. for (i = 0; i < MAX; i++) { System. out. print("Enter line of text: "); line = in. next. Line(); paragraph[i] = line; //Add line as array element } // Write paragraph to file try { fw = new File. Writer("data. txt"); // Open pw = new Print. Writer(fw); for (i = 0; i < MAX; i++) pw. println(paragraph[i]); fw. close(); // Close } catch (IOException e) { System. out. println("Error writing to file"); } James Tam

File IO: Read Data From File try { fr = new File. Reader("data. txt");

File IO: Read Data From File try { fr = new File. Reader("data. txt"); br = new Buffered. Reader(fr); line = br. read. Line(); // Open if (line == null) System. out. println("Empty file, nothing to read"); while (line != null) { System. out. println(line); line = br. read. Line(); } fr. close(); // Close } catch (File. Not. Found. Exception e) { System. out. println("Could not open data. txt"); } catch (IOException e) { System. out. println("Trouble reading from data. txt"); } James Tam

After This Section You Should Now Know • How to write to files with

After This Section You Should Now Know • How to write to files with Java classes • File. Writer • Print. Writer • How to reading text information from files with Java classes • File. Reader • Buffered. Reader James Tam

Java Packages • Packages, a method of subdividing a Java program and grouping classes

Java Packages • Packages, a method of subdividing a Java program and grouping classes One source reference: https: //docs. oracle. com/javase/tutorial/java. OO/accesscontrol. html James Tam

Decomposing Object-Oriented Programs Only By Classes • Works well for small programs e. g.

Decomposing Object-Oriented Programs Only By Classes • Works well for small programs e. g. , The first problem solving assignment (2 D array of references), hierarchies assignment James Tam

Decomposing Larger Object-Oriented Programs • There is another tool to group related classes, packages.

Decomposing Larger Object-Oriented Programs • There is another tool to group related classes, packages. • Java. lang: classes that included with the ‘core’ portion of the Java language: - String - Math - : • Java. util. zip: classes that allow for the reading and writing to zip and gzip compressed files: - Zip. Input. Stream - Zip. Output. Stream - : • Java. awt: the original collection of classes used for creating graphical user interfaces: - Button - Menu - : • Javax. swing: the new collection of classes used for creating graphical user interfaces James Tam

Benefits Of Employing Packages • Increased ease finding a class • Can be used

Benefits Of Employing Packages • Increased ease finding a class • Can be used to prevent naming conflicts java. util Timer Scanner Random Javax. swing Timer JButton JFrame • An additional permission level (package level) may be set to allow certain classes to be instantiated only within the methods of the classes that belong to the same package James Tam

Defining A Package • Used to group a number of classes together into one

Defining A Package • Used to group a number of classes together into one related package • Format (done at the top of a class definition) package <package name>; • Example: package pack 1; public class Integer. Wrapper {. . . } James Tam

Fully Qualified Names: Includes Package package name • pack 3. Open. Foo. to. String()

Fully Qualified Names: Includes Package package name • pack 3. Open. Foo. to. String() class name method name pack 3. Closed. Foo. to. String() James Tam

Importing Packages • Importing all classes from a package (generally regarded as bad practice

Importing Packages • Importing all classes from a package (generally regarded as bad practice because it may allow naming conflicts to occur) Format import <package name>. *; Example import java. util. *; • Importing a single class from a package Format import <package name>. <class name>; Example import java. util. Vector; James Tam

Importing Packages (2) • When you do not need an import statement: - When

Importing Packages (2) • When you do not need an import statement: - When you are using the classes in the java. lang package. - You do not need an import statement in order to use classes which are part of the same package • Excluding the import (from classes other than those from java. lang) requires that the full name be provided: java. util. Random generator = new java. util. Random (); Vs. import java. util. Random; Random generator = new Random (); James Tam

Default Package • If you do not use a package statement then the class

Default Package • If you do not use a package statement then the class implicitly becomes part of a default package. • All classes which reside in the same directory are part of the default package for that program. James Tam

Fully Qualified Names: Matches Directory Structure • pack 3. Open. Foo. to. String() :

Fully Qualified Names: Matches Directory Structure • pack 3. Open. Foo. to. String() : package name home class name 219 method name examples package. Example pack 3 Open. Foo. java { to. String() {…} } Closed. Foo. java James Tam

Where To Match Classes To Packages 1. In directory structure: The classes that belong

Where To Match Classes To Packages 1. In directory structure: The classes that belong to a package must reside in the directory with the same name as the package (previous slide). 2. In the class source code: At the top class definition you must indicate the package that the class belongs to. • Format: package <package name>; <visibility – public or package> class <class name> { } James Tam

Class Level Access: Public, Package • Example (classes in package ‘pack 3’) Open. Foo.

Class Level Access: Public, Package • Example (classes in package ‘pack 3’) Open. Foo. java package pack 3; public class Open. Foo { : } Closed. Foo. java package pack 3; class Closed. Foo { : } James Tam

Class Level Access: Public, Package (2) • Example (classes in package ‘pack 3’) Open.

Class Level Access: Public, Package (2) • Example (classes in package ‘pack 3’) Open. Foo. java package pack 3; public class Open. Foo { : } Public access: Class can be instantiated by classes that aren’t a part of package pack 3 Closed. Foo. java package pack 3; class Closed. Foo { : } Package access (default): Class can only be instantiated by classes that are a part of package pack 3 James Tam

Sun’s Naming Conventions For Packages • Based on Internet domains (registered web addresses) •

Sun’s Naming Conventions For Packages • Based on Internet domains (registered web addresses) • e. g. , www. tamj. com. tam. games j. productivity James Tam

Sun’s Naming Conventions For Packages • Alternatively it could be based on your email

Sun’s Naming Conventions For Packages • Alternatively it could be based on your email address • e. g. , tamj@cpsc. ucalgary. ca ca. ucalgary. cpsc. tamj. games. productivity James Tam

Graphically Representing Packages In UML Package name +Class visible outside the package -Class not

Graphically Representing Packages In UML Package name +Class visible outside the package -Class not visible outside the package James Tam

Packages An Example • Location of the online example: • /home/219/examples/package. Example • (But

Packages An Example • Location of the online example: • /home/219/examples/package. Example • (But you should have guessed the path from the package name) package. Example pack 1 Integer. Wrapper pack 2 Integer. Wrapper pack 3 Closed. Foo Driver Open. Foo James Tam

Graphical Representation Of The Example pack 1 +Integer. Wrapper (Unnamed) +Driver pack 2 +Integer.

Graphical Representation Of The Example pack 1 +Integer. Wrapper (Unnamed) +Driver pack 2 +Integer. Wrapper pack 3 +Open. Foo -Closed. Foo James Tam

Package Example: The Driver Class import pack 3. *; public class Driver { public

Package Example: The Driver Class import pack 3. *; public class Driver { public static void main(String [] argv) { pack 1. Integer. Wrapper iw 1 = new pack 1. Integer. Wrapper(); pack 2. Integer. Wrapper iw 2 = new pack 2. Integer. Wrapper(); System. out. println(iw 1); System. out. println(iw 2); Open. Foo of = new Open. Foo (); System. out. println(of); of. manipulate. Foo(); } } James Tam

Package Example: Package Pack 1, Class Integer. Wrapper package pack 1; public class Integer.

Package Example: Package Pack 1, Class Integer. Wrapper package pack 1; public class Integer. Wrapper { private int num; public Integer. Wrapper() { num = (int) (Math. random() * 10); } public Integer. Wrapper(int new. Value) { num = new. Value; } public void set. Num(int new. Value) { num = new. Value; } James Tam

Package Example: Package Pack 1, Class Integer. Wrapper (2) public int get. Num() {

Package Example: Package Pack 1, Class Integer. Wrapper (2) public int get. Num() { return(num); } public String to. String() { String s = new String (); s = s + num; return(s); } James Tam

Package Example: Package Pack 2, Class Integer. Wrapper package pack 2; public class Integer.

Package Example: Package Pack 2, Class Integer. Wrapper package pack 2; public class Integer. Wrapper { private int num; public Integer. Wrapper() { num = (int) (Math. random() * 100); } public Integer. Wrapper(int new. Value) { num = new. Value; } public void set. Num(int new. Value) { num = new. Value; } James Tam

Package Example: Package Pack 2, Class Integer. Wrapper (2) public int get. Num() {

Package Example: Package Pack 2, Class Integer. Wrapper (2) public int get. Num() { return(num); } public String to. String() { String s = new String (); s = s + num; return(s); } } James Tam

Package Example: Package Pack 3, Class Open. Foo package pack 3; public class Open.

Package Example: Package Pack 3, Class Open. Foo package pack 3; public class Open. Foo { private boolean bool; public Open. Foo() { bool = true; } public void manipulate. Foo() { Closed. Foo cf = new Closed. Foo (); System. out. println(cf); } public boolean get. Bool() { return bool; } public void set. Bool(boolean new. Value) { bool = new. Value; } public String to. String(){ String s = new String (); s = s + bool; return(s); } } James Tam

Package Example: Package Pack 3, Class Closed. Foo package pack 3; class Closed. Foo

Package Example: Package Pack 3, Class Closed. Foo package pack 3; class Closed. Foo { private boolean bool; public Closed. Foo () { bool = false; } public boolean get. Bool() { return bool; } public void set. Bool(boolean new. Value) { bool = new. Value; } public String to. String() { String s = new String(); s = s + bool; return(s); } } James Tam

Updated Levels Of Access Permissions: Attributes And Methods • Private “-” - Can only

Updated Levels Of Access Permissions: Attributes And Methods • Private “-” - Can only access the attribute/method in the methods of the class where it’s originally defined. • Protected “#” - Can access the attribute/method in the methods of the class where it’s originally defined or the subclasses of that class or in classes of the same package. • Package “~” symbol for this permission level - Can access the attribute/method from the methods of the classes within the same package - For Java: If the level of access (attribute or method) is unspecified in a class definition this is the default level of access • Public “+” - Can access attribute/method anywhere in the program James Tam

Updated Levels Of Access Permissions Accessible to Same class Access level Public Protected Package

Updated Levels Of Access Permissions Accessible to Same class Access level Public Protected Package Private Class in same package Subclass in Not a a different subclass, package different package Yes Yes No Yes No No No James Tam

Updated Levels Of Access Permissions Accessible to Same class Class in same Subclass in

Updated Levels Of Access Permissions Accessible to Same class Class in same Subclass in a package different package Not a subclass, different package Yes: e. g. , #1 Yes: e. g. , #5 Yes: e. g. , #9 Yes: e. g. , #13 Yes: e. g. , #2 Yes: e. g. , #6 Yes: e. g. , #10 No: e. g. , #14 Yes: e. g. , #3 Yes: e. g. , #7 No: e. g. , #11 No: e. g. , #15 Yes: e. g. , #4 No: e. g. , #8 No: e. g. , #12 No, e. g. , #16 Access level Public Protected Package Private James Tam

Access Permissions: Example • Location of the example: • /home/219/examples/package. Example. Permissions James Tam

Access Permissions: Example • Location of the example: • /home/219/examples/package. Example. Permissions James Tam

Access Permissions: Examples pack 1 +Class. One +Class. Two (Unnamed) +Driver pack 2 +Class.

Access Permissions: Examples pack 1 +Class. One +Class. Two (Unnamed) +Driver pack 2 +Class. Three James Tam

Levels Of Permission, Same Class • Within the methods of the class, all attributes

Levels Of Permission, Same Class • Within the methods of the class, all attributes and methods may be accessed. // Package: pack 1 public class Class. One { public int num 1; protected int num 2; int num 3; private int num 4; public Class. One { num 1 = 1; num 2 = 2; num 3 = 3; num 4 = 4; } } () // // Example #1 #2 #3 #4 James Tam

Levels Of Permission, Acessible In Class In The Same Package pack 1; public class

Levels Of Permission, Acessible In Class In The Same Package pack 1; public class Class. One { public int num 1; protected int num 2; int num 3; private int num 4; } package pack 1; public class Class. Two { private Class. One c 1; public Class. Two () { c 1 = new pack 1. Class. One (); c 1. num 1 = 1; // Example c 1. num 2 = 2; // Example c 1. num 3 = 3; // Example // c 1. num 4 = 4; // Example } } #5 #6 #7 #8 James Tam

Levels Of Permission, Subclass In Different Package pack 1; public class Class. One {

Levels Of Permission, Subclass In Different Package pack 1; public class Class. One { public int num 1; protected int num 2; int num 3; private int num 4; } package pack 2; import pack 1. Class. One; public class Class. Three extends Class. One { private Class. One c 1; public Class. Three () { super. num 1 = 1; //Example #9 super. num 2 = 2; // Example #10 // super. num 3 = 3; // Example #11 // super. num 4 = 4; // Example #12 } } James Tam

Levels Of Permission, Not A Subclass, Not In Same Package pack 1; public class

Levels Of Permission, Not A Subclass, Not In Same Package pack 1; public class Class. One { public int num 1; protected int num 2; int num 3; private int num 4; } public class Driver { public static void main (String [] args) { pack 1. Class. One c 1 = new pack 1. Class. One (); c 1. num 1 = 1; // Example // c 1. num 2 = 2; // Example // c 1. num 3 = 3; // Example // c 1. num 4 = 4; // Example } } #13 #14 #15 #16 James Tam

After This Section You Should Now Know • How packages work in Java -

After This Section You Should Now Know • How packages work in Java - How to utilize the code in pre-defined packages - How to create your own packages • How the 4 levels of access permission work in conjunction with classes in the same package, sub classes and classes that are neither in the same subclass nor in the same package. James Tam