object-oriented programming and java part 3 csc 212
Post on 21-Dec-2015
240 views
TRANSCRIPT
![Page 1: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/1.jpg)
Object-Oriented Programming Object-Oriented Programming and Javaand Java
Part 3Part 3
CSC 212
![Page 2: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/2.jpg)
Announcements
By the end of this week you should have read all of Chapter 1 and be into Chapter 2 in the textbook.
Decide if you need additional reading on Java. This is the last review section.
![Page 3: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/3.jpg)
So What’s a Package?
Package = Grouping of related classesEach file starts with “package <package_name>;”Packages are named after their domain
e.g., package Edu.Canisius.Aries;
Class names formally include package name, so names reused only outside of package
![Page 4: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/4.jpg)
Using Packaged Classes
By qualified name r1 = new Edu.Canisius.Student(“Bob”, 1050);
By specific import import Edu.Canisius.Student;r1 = new student(“Bob”, 1050);
By package import import Edu.Canisius.*; r1 = new student(“Bob”, 1050);
![Page 5: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/5.jpg)
Public/Private vs. Package
Package provides encapsulation in the largeCan treat group of classes as a single unit
Packaging reduces “name space pollution”Less worry about making unique names
![Page 6: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/6.jpg)
Simple Output in Java
Java provides static object, System.out, to perform simple outputAll output is buffered and outputted to screen
System.err is similar, but does not buffer outputMakes use of several static methods:
System.out.print(Object o) – print o.toString() System.out.print(<base_type> b) – output b System.out.println(String s) – print s and then
end the line
![Page 7: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/7.jpg)
Simple Input in Java
Java defines System.in for console input Static object is too simple for most uses
Use the following template instead:java.io.BufferedReader stndin;stndin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
Read single character using int read(); Read line of text with String readLine();
![Page 8: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/8.jpg)
Exceptions
Exception …. an unusual event could lead to erroneous or unexpected resultcould be fatal to a program.
Java automatically detects certain kinds of errorsExceptions allow the programmer to correct
the error
![Page 9: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/9.jpg)
Exceptions
When an exception occurs, execution passes to special code section that could take corrective action
Terminology is ‘throw an exception’ (detection) and ‘catch an exception’ (handling/correction).
![Page 10: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/10.jpg)
Exceptions, cont’d
Java defines a group of standard exceptions (e.g. ,the NullPointerException).
Programmers may define new exceptionsDone by extending Exception class:
public class BadStudentID extends Exception {………
} //end of class BadStudentID
![Page 11: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/11.jpg)
Exceptions, cont’d
Methods should specify thrown exceptionsCompletes abstract description of functionalityDescribes normal and abnormal behavior Important for robustness
3 ways of dealing with thrown exceptions: ignore it (not handle it at all)handle it where it occurshandle it at some other point in the program
![Page 12: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/12.jpg)
Exceptions: Checked and Unchecked Java distinguishes between checked and
unchecked exceptionsChecked exceptions MUST be declared in a
throws clauseUnchecked exceptions can be thrown
anywhere and need not be declared Programmers can define either checked or
unchecked exceptions
![Page 13: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/13.jpg)
Throwing an Exception
Methods should declare exceptions that they might throw, e.g., public void sumLesserOdds(int n)
throws NegativeInputException { if (n < 0)
throw new NegativeInputException(n); …}
![Page 14: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/14.jpg)
Catching an Exception
Try-Catch blocks execute until an exception is thrown
Blocks can list multiple catch statementsExceptions will be caught by first matching
catch statement If no statement matches, exception is passed
on to calling method
![Page 15: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/15.jpg)
Finally Clause
Try-Catch blocks can include finally statementAll code executes code in block following finally
Useful for closing open files or other important processing
![Page 16: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/16.jpg)
Catching An Exception
Exceptions are handled in try-catch blocks
public static void main(String args) { try { sumLesserOdds(2); sumLesserOdds(-1); } catch (NegativeInputException nie) { System.out.println(“Oops. Passed a negative number”); } …
![Page 17: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/17.jpg)
Throwing an Exception
Methods should also declare exceptions they do not catch and will therefore pass on, e.g.,
public void calculateOdds(int n)throws NegativeInputException {
sumLesserOdds(n); …}
![Page 18: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/18.jpg)
Exceptions: Checked and Unchecked BUT defining unchecked exceptions is BAD
PRACTICE (The Java Programming Language, Arnold and Gosling, p. 374) :“By [defining unchecked exceptions] you lie about the
exception (that it is thrown by the [Java] runtime [system]).”
“You also invalidate the assumptions of programmers using your method that they can understand the method’s behavior by reading its throws clause.”
![Page 19: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/19.jpg)
Checked v. Unchecked ExceptionsThrowable
ExceptionError
Subclasses of Error are unchecked exceptions. These are generally unrecoverable errors detected by the Java runtime system that cannot usefully be caught.
Subclasses of Exception (except RuntimeException) are checked exceptions. These represent errors that user-written code might detect.
Runtime Exception
Subclasses of RunTimeExceptionare unchecked exceptions. These are meant to represent errors detected by the Java runtime system.
![Page 20: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/20.jpg)
javadoc Comments
javadoc is a program to automatically generate HTML pages documenting Java classesProvides comments for all fields & methodsMakes code distribution & reuse easierWill be required for all homeworksUses formatted comments within source code
![Page 21: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/21.jpg)
Commenting Source Code
javadoc comments go from /** to */.
/** This is a simple, one-line javadoc comment */
/** * This is a valid multiline javadoc comment. * ‘*’s at the start of each line aren’t included * in the HTML documentation, however. */
/** Another valid multiline comment*/
![Page 22: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/22.jpg)
Placing javadoc Comments
javadoc comments must immediately precede the class, field, method, or constructor declaration /** This comment is not good */import com.ibm.JikesRVM.*; public class fubar { … }
/** This comment is accepted, however */
public class fubar2 { … }
![Page 23: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/23.jpg)
javadoc Comment Construction
All comments contain two sectionsThe main description – enables the
programmer to textually describe the class or class member
The tag section – block tags highlight important information within the documentation
![Page 24: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/24.jpg)
javadoc Comment Construction
All comments must contain legal HTMLHTML formatting can be embedded inside
comments:
/** This is a legal <b>partially bold</b> comment */
Comments cannot include “<”, “>”, or “&” since they are not legal in HTML code
Use “<”, “>”, and “&”, respectively
![Page 25: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/25.jpg)
Importance of the First Sentence
javadoc uses the first sentence as a brief overview of the memberUses sentence in class summary at top of
pageSentence ends with first block tag or period
followed by a space, tab or newline
![Page 26: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/26.jpg)
Declaration with Multiple Fields
Multiple fields makes for ugly comments/** The location of the point */protected int x, y;
becomes:public int x
The location of the pointpublic int y
The location of the point
![Page 27: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/27.jpg)
Class Block Tags
@author name @author <a href=http://www-cs.canisius.edu/~hertzm>Matthew Hertz</a>
Adds an author entry to the top of the page. You can use multiple author tags (they will be in a list separated by “,”s)
![Page 28: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/28.jpg)
Method Block Tags
@param parameter-name description@param n The number of elements to average
Appears in parameter section of method doc Multiple parameter tags are encouraged Should define parameters in order declared
@return description@return Sum of lesser odd positive numbers Appears in return section of method
![Page 29: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/29.jpg)
Method Block Tags
@throws class-name description@throws NegativeValueException Exception thrown when a negative number passed as parameter
Listed in “Throws” section of methodMultiple @throws allowed & encouraged
![Page 30: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/30.jpg)
Designing Java Programs
The most important programming stepAlso the most lucrativeAnd should be where the most time is spent
In Java, begin by dividing into classesClean design makes portable, reusable codeBad design makes coding hard to impossible
![Page 31: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/31.jpg)
Class Design
Important to step away from exact problem Instead, consider:
What are the important actions?Can these be made into independent actors?Can we perform these actions generically
(e.g., without specializing them for the data)?
![Page 32: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/32.jpg)
Class Design
Designing classes is computer science at its most creative Important to consider all possibilitiesThis is also CSC at its most lazy
Keep an eye to reusing past solutions
We will spend more time on this in lab than anything else
![Page 33: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/33.jpg)
Testing
Ideal: code that we can prove will workReality: way to time consuming to proveWhat other difficulties are there?
Instead, test code on many different possible inputs
![Page 34: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/34.jpg)
Testing
What inputs are important to consider?
![Page 35: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/35.jpg)
Testing Plans
Useful way of organizing testing Each test in test plan has 5 parts
Purpose of test – written in English, this provides a “sanity check” on tests
Test data set – what input will you testFunction(s) to be test – what code is testedExpected results – what is the correct resultActual results – what is the actual result?
![Page 36: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/36.jpg)
Debugging
Where most of the time is spentAlso an important and very lucrative skill
Debugging is akin to solving mysteriesUses many of the same skills and techniquesOddly, my script for “Sherlock Holmes and the
Mutating Variable” not well received
![Page 37: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/37.jpg)
How to Debug Code
Debugging is the antithesis of designingRequires organized, methodical approachNever gets easier, only faster with experience
![Page 38: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/38.jpg)
How to Debug Code
Scientific approach to debuggingReview code and see if you can find problemRevert back to where things workedTest methods individually to see if they workUntil you find the error, make 1 change at a
time before re-testingExecute the code by hand
![Page 39: Object-Oriented Programming and Java Part 3 CSC 212](https://reader035.vdocuments.net/reader035/viewer/2022062320/56649d585503460f94a3767c/html5/thumbnails/39.jpg)
Daily Quiz
Write a Java method that accepts two integer arrays as input (e.g., a & b) and outputs a third array (e.g., c), such that c[i] = a[i] * b[i]. The method should throw a
ArraySizeMismatchException exception if the two arrays do not have the same length
You may assume the exception object exists. Its constructor signature is:public ArraySizeMismatchException(int firstArraySize, int secondArraySize)