export_java chapter 8 Flashcards

1
Q

what is the class represent ?

A

A class represents a single concept from the problem domain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what should be the name of the class ?

A

Name for a class should be a noun that describes concept

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Concepts from mathematics:

A

Point
Rectangle
Ellipse

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what are actors ?

A

Actors (end in -er, -or)– objects do some kinds of work for you:
Scanner
Random // better name: RandomNumberGenerator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what are the utilty classes ?

A

no objects, only static methods and constants:

Mathition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what are the program saters ?

A

only have a main method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Don’t turn actions into classes

A

Paycheck is a better name than ComputePaycheckion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the rule of thumb for finding classes?

A

Answer: Look for nouns in the problem description.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Your job is to write a program that plays chess. Might

ChessBoard be an appropriate class? How about MovePiece?

A

Answer: Yes (ChessBoard) and no (MovePiece).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what is cohesion?

A

A class should represent a single concept

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

The public interface of a class is …….

A
cohesive if all of its features
are related to the concept that the class represents
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

• This class lacks cohesion:

A
public class CashRegister
{
public void enterPayment(int dollars, int quarters,
int dimes, int nickels, int pennies)
...
public static final double NICKEL_VALUE = 0.05;
public static final double DIME_VALUE = 0.1;
public static final double QUARTER_VALUE = 0.25;
...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

solutions: • CashRegister, as described above, involves two concepts:
cash register and coin

A
• Solution: Make two classes:
public class Coin
{
public Coin(double aValue, String aName) { ... }
public double getValue() { ... }
...
}
public class CashRegister
{
public void enterPayment(int coinCount, Coin coinType)
{ ... }
...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what is coupling ?

A

• A class depends on another if it uses objects of that class
• CashRegister depends on Coin to determine the value of the
payment
• Coin does not depend on CashRegister

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

• High coupling

A

Many class dependencies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Minimize coupling to

A

o minimize the impact of interface changes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

points of coupling ?

A

• To visualize relationships draw class diagrams

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

• UML:

A

Unified Modeling Language

• Notation for object-oriented analysis and design

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Dependency

A

https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/image3ergqx-14A3F6ADC191295129F.png

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

High and Low Coupling Between Classes

A

https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imageu4cdqx-14A3F72369F0E0E1A92.png

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why is the CashRegister class from Chapter 4 not cohesive?

A

Answer: Some of its features deal with payments, others with

coin values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why does the Coin class not depend on the CashRegister class?

A

Answer: None of the Coin operations require the CashRegister

class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Why should coupling be minimized between classes?

A
Answer: If a class doesn’t depend on another, it is not affected
by interface changes in the other class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

• Accessor:

A

Does not change the state of the implicit parameter:

double balance = account.getBalance();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
• Mutator:
Modifies the object on which it is invoked: | account.deposit(1000);
26
• Immutable class:
``` Has no mutator methods (e.g., String): String name = "John Q. Public"; String uppercased = name.toUpperCase(); // name is not changed ```
27
It is safe to give out references to objects of immutable classes;
no code can modify the object at an unexpected time
28
``` Is the substring method of the String class an accessor or a mutator? ```
``` Answer: It is an accessor — calling substring doesn’t modify the string on which the method is invoked. In fact, all methods of the String class are accessors. ```
29
Is the Rectangle class immutable?
Answer: No — translate is a mutator.
30
Side effect of a method:
Any externally observable data modification: harrysChecking.deposit(1000);
31
• Modifying explicit parameter
``` can be surprising to programmers— avoid it if possible: public void addStudents(ArrayList studentNames) { while (studentNames.size() > 0) { String name = studentNames.remove(0); // Not recommended . . . ```
32
Side Effects• This method has the expected side effect of modifying the implicit parameter and the explicit parameter other:
``` public void transfer(double amount, BankAccount other { balance = balance – amount; other.balance = other.balance + amount; } ```
33
• Another example of a side effect is output:
public void printBalance() // Not recommended { System.out.println("The balance is now $" + balance); } Bad idea: Message is in English, and relies on System.out
34
• Decouple
input/output from the actual work of your classes
35
• Minimize side effects t
that go beyond modification of the implicit | parameter
36
If a refers to a bank account, then the call a.deposit(100) | modifies the bank account object. Is that a side effect?
Answer: It is a side effect; this kind of side effect is common in object-oriented programming.
37
``` Consider the DataSet class of Chapter 6. Suppose we add a method void read(Scanner in) { while (in.hasNextDouble()) add(in.nextDouble()); } Does this method have a side effect other than mutating the data set? ```
Answer: Yes — the method affects the state of the Scanner | parameter.
38
Common Error: Trying to Modify Primitive Type | Parameters
``` • void transfer(double amount, double otherBalance) { balance = balance – amount; otherBalance = otherBalance + amount; } • Won’t work ```
39
• Scenario: double savingsBalance = 1000; harrysChecking.transfer(500, savingsBalance); System.out.println(savingsBalance);
• In Java, a method can never change parameters of primitive | type
40
Common Error: Trying to Modify Primitive Type | Parameters
``` double savingsBalance = 1000; harrysChecking.transfer(500, savingsBalance); System.out.println(savingsBalance); ... void transfer(double amount, double otherBalance) { balance = balance - amount; otherBalance = otherBalance + amount; } ```
41
Common Error: Trying to Modify Primitive Type | Parameters
``` double savingsBalance = 1000; harrysChecking.transfer(500, savingsBalance); System.out.println(savingsBalance); ... void transfer(double amount, double otherBalance) { balance = balance - amount; otherBalance = otherBalance + amount; } ```
42
• Call by value:
Method parameters are copied into the | parameter variables when a method starts
43
• Call by reference:
: Methods can modify parameters
44
DIK
• Java has call by value
45
• A method can change state of object reference parameters, but
cannot replace an object reference with another
46
Call by Value and Call by Reference
``` public class BankAccount { public void transfer(double amount, BankAccount otherAccount) { balance = balance - amount; double newBalance = otherAccount.balance + amount; otherAccount = new BankAccount(newBalance); // Won't work } } ```
47
Call by Value Example
harrysChecking.transfer(500, savingsAccount);
48
• Precondition:
Requirement that the caller of a method must | meet
49
• Publish preconditions so the caller won’t call methods with bad parameters:
``` /** Deposits money into this account. @param amount the amount of money to deposit (Precondition: amount >= 0) */ ```
50
• Typical use: Preconditions
1. To restrict the parameters of a method 2. To require that a method is only called when the object is in an appropriate state
51
• If precondition is violated,
method is not responsible for | computing the correct result. It is free to do anything
52
• Method may throw exception if precondition
if precondition violated — more in Chapter 11: if (amount < 0) throw new IllegalArgumentException(); balance = balance + amount;
53
• Method doesn’t have to test for precondition.
``` (Test may becostly): // if this makes the balance negative, it's the // caller's fault balance = balance + amount; ```
54
Preconditions | • Method can do an assertion check:
assert amount >= 0; balance = balance + amount; To enable assertion checking: java -enableassertions MainClass You can turn assertions off after you have tested your program, so that it runs at maximum speed
55
Preconditions | • Many beginning programmers silently return to the caller
if (amount < 0) return; // Not recommended; hard to debug balance = balance + amount;
56
Syntax 8.1 Assertion
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imagecfjvqx-14A3F7F09991D888B4A.png
57
•Postcondition:
requirement that is true after a method has completed
58
• If method call is in accordance with preconditions,
it must ensure | that postconditions are valid
59
• There are two kinds of postconditions:
``` • The return value is computed correctly • The object is in a certain state after the method call is completed • /** Deposits money into this account. (Postcondition: getBalance() >= 0) @param amount the amount of money to deposit (Precondition: amount >= 0) */ ```
60
Postconditions | • Don’t document trivial postconditions
that repeat the @return | clause
61
• Formulate pre- and postconditions only in terms of the interface of the class: like:
amount <= balance // wrong postcondition formulation
62
• Contract: in postondition
If caller fulfills preconditions, method must fulfill | postconditions
63
Why might you want to add a precondition to a method that you provide for other programmers?
Answer: Then you don’t have to worry about checking for | invalid values — it becomes the caller’s responsibility
64
When you implement a method with a precondition and you notice that the caller did not fulfill the precondition, do you have to notify the caller?
Answer: No — you can take any action that is convenient for | you.
65
Static Methods
Every method must be in a class • A static method is not invoked on an object • Why write a method that does not operate on an object • Common reason: encapsulate some computation that involves only numbers. • Numbers aren’t objects, you can’t invoke methods on them. E.g. x.sqrt() can never be legal in Java
66
• Example:Static Methods
``` public class Financial { public static double percentOf(double p, double a) { return (p / 100) * a; } // More financial methods can be added here. } ```
67
• Call with class name instead of object:
double tax = Financial .percentOf(taxRate, total);
68
``` Static Methods • If a method manipulates a class that you do not own, ```
you cannot | add it to that class
69
• A static method solves this problem:
``` public class Geometry { public static double area(Rectangle rect) { return rect.getWidth() * rect.getHeight(); } // More geometry methods can be added here. } ```
70
• main is static
there aren’t any objects yet
71
Suppose Java had no static methods. How would you use the Math.sqrt method for computing the square root of a number x?
``` Answer: Math m = new Math(); y = m.sqrt(x); ```
72
The following method computes the average of an array list of numbers: public static double average(ArrayList values) Why must it be a static method?
``` Answer: You cannot add a method to the ArrayList class — it is a class in the standard Java library that you cannot modify. ```
73
``` A static variable belongs to the class, not to any object of the class: public class BankAccount { ... private double balance; private int accountNumber; private static int lastAssignedNumber = 1000; } ```
• If lastAssignedNumber was not static, each instance of BankAccount would have its own value of lastAssignedNumbe
74
DIK Static Variables
``` • public BankAccount() { // Generates next account number to be assigned lastAssignedNumber++; // Updates the static variable accountNumber = lastAssignedNumber; // Sets the instance variable } ```
75
A Static Variable and Instance Variables
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/image6desqx-14A3F8704F94D67FBE9.png
76
Static Variables | • Three ways to initialize:
``` 1. Do nothing. variable is initialized with 0 (for numbers), false (for boolean values), or null (for objects) 2. Use an explicit initializer, such as public class BankAccount { private static int lastAssignedNumber = 1000; // Executed once, } 3. Use a static initialization block ```
77
• Static variables should always be declared as
private
78
Exception: Static constants, which may be either private or public:
``` public class BankAccount { ... public static final double OVERDRAFT_FEE = 5; // Refer to it as BankAccount.OVERDRAFT_FEE } ```
79
tip
• Minimize the use of static variables (static final variables are ok)
80
Name two static variables of the System class.
Answer: System.in and System.out.
81
``` Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and variables static. Then main can call the other static methods, and all of them can access the static variables. Will Harry’s plan work? Is it a good idea? ```
Answer: Yes, it works. Static methods can access static variables of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs.
82
• Scope of variable:
Region of program in which the variable can | be accessed
83
DIK
• Scope of a local variable extends from its declaration to end of the block that encloses it
84
Scope of Local Variables | • Sometimes the same variable name is used in two methods:
``` public class RectangleTester { public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; } public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30); double a = area(r); System.out.println(r); } } • These variables are independent from each other; their scopes are disjoint ```
85
• Scope of a local variable cannot contain the definition of another variable with the same name:
tippp 
86
• However, can have local variables with identical names
``` if scopes do not overlap: if (x >= 0) { double r = Math.sqrt(x); ... } // Scope of r ends here else { Rectangle r = new Rectangle(5, 10, 20, 30); // OK - it is legal to declare another r here ... } ```
87
Overlapping Scope
* A local variable can shadow a variable with the same name | * Local scope wins over class scope :
88
Overlapping Scope | Generally, shadowing an instance variable is
``` poor code —error-prone, hard to read • Exception: when implementing constructors or setter methods, it can be awkward to come up with different names for instance variables and parameters OK: public Coin(double value, String name) { this.value = value; this.name = name; } ```
89
``` Consider the following program that uses two variables named r. Is this legal? public class RectangleTester { public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; } public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30); double a = area(r); System.out.println(r); } } ```
Answer: Yes. The scopes are disjoint.
90
What is the scope of the balance variable of the BankAccount | class?
``` Answer: It starts at the beginning of the class and ends at the end of the class. ```
91
• Package:
Set of related classes
92
• Important packages in the Java library:
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/selection_173-14A3F9050CA11D32B11.png
93
Organizing Related Classes into Packages
• To put classes in a package, you must place a line | package packageName ;
94
DIY
• Package name consists of one or more identifiers separated by periods
95
Organizing Related Classes into Packages
• Default package has no name, no package statement
96
Syntax 8.2 Package Specification
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imagenxqtqx-14A3F921142439FD2D3.png
97
Importing Packages
• Can always use class without importing: java.util.Scanner in = new java.util.Scanner(System.in); • Tedious to use fully qualified name • Import lets you use shorter class name: import java.util.Scanner; ... Scanner in = new Scanner(System.in)
98
• Can import all classes in a package:
import java.util.*;
99
• Never need to import
java.lang
100
tip
You don’t need to import other classes in the same package
101
• Use packages to avoid name clashes
java.util.Timer vs. javax.swing.Timer
102
tip
java.util.Timer vs. javax.swing.Timer
103
• Recommendation:
start with reversed domain name: | com.horstmann.bigjava
104
for Britney Walters’ classes | walters@cs.sjsu.edu
• edu.sjsu.cs.walters :
105
com/horstmann/bigjava/Financial.java
• Path name should match package name:
106
Package and Source Files | • Base directory:
holds your program's Files
107
Path name, relative to base directory, must match package | name:
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imagev0prqx-14A3F98E35F03D5E501.png
108
Which of the following are packages? a. java b. java.lang c. java.util d. java.lang.Math
Answer: a. No b. Yes c. Yes d. No
109
Is a Java program without import statements limited to using the default and java.lang packages?
Answer: No — you simply use fully qualified names for all other classes, such as java.util.Random and java.awt.Rectangle.
110
Suppose your homework assignments are located in the directory /home/me/cs101 (c:\Users\me\cs101 on Windows). Your instructor tells you to place your homework into packages. In which directory do you place the class hw1.problem1.TicTacToeTester?
Answer: /home/me/cs101/hw1/problem1 or, on | Windows, c:\Users\me\cs101\hw1\problem1
111
The Explosive Growth of Personal Computers
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imageu5ppqx-14A3F9A1DEC33F0E742.png
112
The Explosive Growth of Personal Computers
simplify the task of writing classes that contain many test cases • JUnit: http://junit.org • Built into some IDEs like BlueJ and Eclipse
113
• Customary that name of the test class ends in Test:
``` import org.junit.Test; import org.junit.Assert; public class CashRegisterTest { @Test public void twoPurchases() { CashRegister register = new CashRegister(); register.recordPurchase(0.75); register.recordPurchase(1.50); register.enterPayment(2, 0, 5, 0, 0); double expected = 0.25; Assert.assertEquals(expected, register.giveChange(), EPSILON); } // More test cases . . . } ```
114
• If all test cases pass, the JUnit tool shows a green bar:
https://s3.amazonaws.com/classconnection/655/flashcards/7082655/png/imagefrmjqx-14A3F9CBAA148FBB8D0.png
115
``` Provide a JUnit test class with one test case for the Earthquake class in Chapter 5. ```
``` Answer: Here is one possible answer, using the JUnit 4 style. public class EarthquakeTest { @Test public void testLevel4() { Earthquake quake = new Earthquake(4); Assert.assertEquals("Felt by many people, no destruction”, quake.getDescription()); } } ```
116
What is the significance of the EPSILON parameter in the | assertEquals method?
Answer: It is a tolerance threshold for comparing floating-point numbers. We want the equality test to pass if there is a small roundoff error.