big java chapters 3-6. object-oriented concepts(review) encapsulation – hiding unimportant details...

28
Big Java Big Java Chapters 3-6 Chapters 3-6

Upload: baldwin-austin

Post on 18-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Big JavaBig JavaChapters 3-6Chapters 3-6

Page 2: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Object-Oriented ConceptsObject-Oriented Concepts (review)(review)

• Encapsulation – hiding unimportant details• Black box – something that magically

“does its thing”• Abstraction – taking away inessential

features• Example: car

– if engine control module fails, replace it– mechanic can provide inputs, test outputs– doesn’t need to know how it works

• OO challenge: finding the right abstractions (what “black boxes” do we need to solve the problem at hand?)

Page 3: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Object-Oriented ConceptsObject-Oriented Concepts (review)(review)

• How would you represent:– a bank account?– a book?– a library?– a customer?– an oil field?– a mutual fund?– an employee?

Page 4: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

javadoc commentsjavadoc comments

Remember the API had a standard format. User-defined classes can easily create html documentation in that same format, by inserting comments that meet certain specifications:

• Start with /**• First sentence describes purpose• @ tags specify information (e.g., @param,

@return, @throws, @author, @version)• run javadoc from command line or Eclipse

to generate html pages

Page 5: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

BankAccountBankAccount

• See Eclipse notes for example of creating class with comments

• As in C++, constructors have name of class, can be overloaded

• Instance fields should be made private, accessors and modifiers (getters/setters) are used

• Additional methods are defined as needed

Page 6: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

More on VariablesMore on Variables

• Instance variables– each object has its own copy (as in C++)– objects are automatically garbage collected

(unlike C++!)– fields are initialized with a default value (e.g.,

0, null) if not explicitly set in constructor. Still good to do your own initialization.

– NullPointerException if you forget to call new

• Local variables– must be explicitly initialized– only exist inside method (as in C++)

Page 7: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Reading AssignmentReading Assignment

• Read Random Fact 3.1 (Electronic Voting Machines) on page 110 and be prepared to discuss

• Read Shape Classes (3.9) and be prepared to discuss

Page 8: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

On to Chapter 4…

Fundamental Data Types

Page 9: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Numeric Data Types (review)Numeric Data Types (review)

• Integer values can be represented exactly, but numeric operations may result in overflow

• Floating point values may not be exact, so rounding errors may occur (shouldn’t use == with floating point values, use tolerance)

• double is therefore not appropriate for financial calculations

• java.math has BigInteger and BigDecimal classes which are slow but have better size/precision. Must use add, subtract and multiply (no operator overloading in Java)

• READ: Random Fact 4.1, Pentium Floating-Point Bug on page 139

Page 10: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Constant valuesConstant values

• preceded by keyword final (vs const in C++)• naming convention is all uppercase• e.g.,

final double QUARTER_VALUE = 0.25;

• if used in a class, often use keyword static, meaning constant belongs to the class:public static final double DIME_VALUE =0.1;

• Math class has some useful constants, e.g.,double circumference = Math.PI * diameter;(vs Math::PI in C++)

Page 11: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Numeric OperationsNumeric Operations

• +, -, *, /, % - same precedence as C++• Math class has a number of static functions (sqrt,

pow, sin, cos, exp, log, round, max, min, etc.)• / of two integers yields an integer result (same as

C++)Quality Tips:

– put space after every Java keyword, but not between a method name and parentheses

– put space around all binary operators– factor out common code– example:

x1=(-b+Math.sqrt (b*b-4*a*c))/(2*a);x2=(-b-Math.sqrt (b*b-4*a*c))/(2*a);becomes:double root = Math.sqrt(b * b – 4 * a * c);x1 = (-b + root) / (2 * a);x2 = (-b – root) / (2 * a);

Page 12: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Numeric Operations, continuedNumeric Operations, continued

• Remember that you may need to round floating point values

double f = 4.35;int n = (int) (100 * f);System.out.println(n); // prints 434!

Replace with:int n = (int) Math.round(100 * f);

• Read: How To 4.1, good review of how to design programs containing numeric computations

Page 13: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

UnicodeUnicode

• C++ and other languages used ASCII to encode characters

• Java uses a 16-bit encoding known as Unicode

• First 128 characters (i.e., English alphabet) are the same as ASCII

• Also includes German umlauts, about 21000 Chinese ideographs and others

• Can encode as escape sequence, e.g. \u00E9 is e’

Page 14: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Reading Input and Formatting NumbersReading Input and Formatting Numbers// required for input from keyboardimport java.util.Scanner; // required for formattingimport java.text.NumberFormat;

public class SalesTax { public static void main(String[] args) { final double TAX_RATE = 0.06;

// 6% sales tax double subtotal, tax, totalCost;

// Calculated values // Set up Scanner for keyboard Scanner scan = new Scanner

(System.in);

System.out.print("Enter the price: "); double price = scan.nextDouble(); System.out.print("Enter the quantity: "); int quantity = scan.nextInt(); subtotal = price * quantity; tax = subtotal * TAX_RATE; totalCost = subtotal + tax;

// Create desired formatting objectsNumberFormat fmt1 =

NumberFormat.getCurrencyInstance(); NumberFormat fmt2 =

NumberFormat.getPercentInstance();

// Print messages using formatting objects System.out.println ("Subtotal: " +

fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + "

at “ + fmt2.format(TAX_RATE)); System.out.println ("Total: " +

fmt1.format(totalCost)); }}

// Can also use System.out.printf for formatted// output – similar to C++ printf// System.out.printf(“Total: %5.2f”, totalCost);

Page 15: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Simple Dialog BoxesSimple Dialog Boxes/**

 * MaxDialog.java*/

import javax.swing.*;

public class MaxDialog {      public static void main(String[] args) {    String numStr;    int max=0;    int num, more;    do    {       numStr = JOptionPane.showInputDialog("Enter an integer");      num = Integer.parseInt(numStr);  // must extract integer from string

      if (num > max)          max = num;

        // parentComponent is null, uses default frame      JOptionPane.showMessageDialog(null, "Max so far: " + max);

      more = JOptionPane.showConfirmDialog (null, "Check Another?");    } while (more == JOptionPane.YES_OPTION);  }}

Page 16: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

On to Chapter 5…

Decisions

Page 17: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

DecisionsDecisions

• if, if-else and nested if-else just like C++• use of braces for compound statements

just like C++• Relational operators (> >= < <= == !=)

just like C++• switch is just like C++ (remember break!)• dangling else is a problem in Java, just as

in C++• logical operators (&&, ||, !) just like C++• short-circuit evaluation applies

Page 18: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Comparing StringsComparing Strings

• To compare contents of strings, use equals:if (string1.equals(string2)) . . .

• May prefer to ignore case:if (string1.equalsIgnoreCase(string2)) . . .

• Can use compareTo to find out the relationship (<0 if first is less, ==0 if same, >0 if first is greater):if (string1.compareTo(string2)) < 0) . . .

Order: numbers < uppercase < lowercaseshorter strings < longer strings (e.g., “car” < “cargo”

Page 19: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

String subtletyString subtlety

String nickname = “Rob”;

// Creates a literal string “Rob”

if (nickname == “Rob”) // succeeds

But:String name = “Robert”;

String nickname = name.substring(0, 3);

if (nickname == “Rob”) // fails

Page 20: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Enumerated TypesEnumerated Types

public enum FilingStatus {SINGLE,MARRIED}

FilingStatus status = FilingStatus.SINGLE;

if (status == FilingStatus.SINGLE) . . .

• Often declared inside a class:if (status == TaxReturn.FilingStatus.SINGLE) . . .

• An enumerated type variable can be null

Page 21: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

De Morgan’s LawDe Morgan’s Law

• !(A && B) == !A || !B• !(A || B) == !A && !B

Example:• !(0 < amount && amount < 1000)• !(0 < amount) || !(amount < 1000)• (0 >= amount) || (amount >= 1000)• NOTE: opposite of < is >=, not >

Page 22: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Reading/Homework AssignmentReading/Homework Assignment

Read: • Section 5.5 Test Coverage on page 212• 5.3 Calculate Sample Data Manually on page 213, and • 5.4 Prepare Test Cases Ahead of Time on page 214

Questions to answer:1. What is black-box testing?2. What is white-box testing?3. What are boundary tests? 4. Design a set of test cases for the TaxCalculator program.

That is, list the exact inputs you would test along with the expected outputs.

Turn in this assignment in a .txt file on Blackboard.

Page 23: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

On to Chapter 6…

Iteration

Page 24: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Loops in JavaLoops in Java

• while loops – same as C++• same common errors: infinite loops, off-by-

one• do loops – same as C++• for loops – same as C++ (but with another

useful syntax for collections)• same common errors: forget semicolon if

need empty body, or include semicolon on for statement

• Quality tip: for loops are best for counting loops. Use a while loop for other types (see 6.1 on page 241)

Page 25: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Loops in Java (continued)Loops in Java (continued)

• nested Loops – same as in C++• Quality tip: don’t use != to test the end of

a range, better to use <, <= etc.• sentinel loops – same as in C++

Page 26: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Reading Assignment #1Reading Assignment #1

• How to 6.1 Implementing Loops, page 250• Quality Tip 6.3 Symmetric and Asymmetric

Bounds• Quality Tip 6.4 Count Iterations• Advanced Topic 6.3 Loop and a Half

Problem• Advanced Topic 6.4 break and continue• Reflect on your own coding style as you

read, and be ready to discuss next time.

Page 27: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

Reading Assignment #2Reading Assignment #2

• Advanced Topic 6.5 Loop Invariants, page 261

• Random Fact 6.2 Correctness Proofs, page 263

• Thought question: what loops have you seen/written where this technique might be applicable?

Page 28: Big Java Chapters 3-6. Object-Oriented Concepts(review) Encapsulation – hiding unimportant details Black box – something that magically “does its thing”

ExerciseExercise

• Bring your books to class!• Download Word.java and

SyllableCounter.java from Blackboard• Work through 6.7 Sample Debugging

Session