View
230
Download
2
Embed Size (px)
Citation preview
Object-Oriented Programming Object-Oriented Programming and Javaand Java
Part 3Part 3
CSC 212
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.
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
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);
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
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
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();
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
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).
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
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
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
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); …}
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
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
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”); } …
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); …}
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.”
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.
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
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*/
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 { … }
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
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
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
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
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)
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
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
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
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)?
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
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
Testing
What inputs are important to consider?
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?
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
How to Debug Code
Debugging is the antithesis of designingRequires organized, methodical approachNever gets easier, only faster with experience
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
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)