Académique Documents
Professionnel Documents
Culture Documents
Chapter 8:
Designing Classes
Choosing Classes
Choosing Classes
Scanner
Random // better name: RandomNumberGenerator
What classes would you use for the following problem description:
Cohesion
A class should represent a single concept
The public interface of a class is cohesive if all of its features
are related to the concept that the class represents
This class lacks cohesion:
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;
. . .
}
Cohesion
CashRegister,
Coupling
Coupling
Side Effects
{
balance = balance - amount;
otherBalance = otherBalance + amount;
}
Corrected Version
harrysChecking.transfer(500, savingsAccount);
Static Methods
Harry turns in his homework assignment, a program that plays tictac-toe. His solution consists of a single class with many static
methods. Why is this not an object-oriented solution?
Answer:
Math m = new Math();
double y = m.sqrt(x);
Static Fields
A static field belongs to the class, not to any object of the class.
Also called class field
Assume we wish to create BankAccounts, but we wish the
account numbers to be assigned automatically by the
constructor.
BankAccount accountA = new BankAccount(); // acc. # 1001
BankAccount accountB = new BankAccount(); // acc. # 1002
Static fields have their uses, but they should be used with
caution (static final fields are ok)
Static Fields