Chapter 9

Designing Classes


Chapter Goals


Choosing Classes

Choosing Classes

Self Check

  1. What is the rule of thumb for finding classes?
  2. Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How about NextMove?

Answers

  1. Look for nouns in the problem description
  2. Yes (ChessBoard) and no (NextMove)

Cohesion

Cohesion

Coupling

Coupling


High and Low Coupling between Classes


Self Check

  1. Why is the CashRegister class from Chapter 4 not cohesive?
  2. Why does the Coin class not depend on the CashRegister class?
  3. Why should coupling be minimized between classes?

Answers

  1. Some of its features deal with payments, others with coin values
  2. None of the coin operations require the CashRegister class
  3. If a class doesn't depend on another, it is not affected by interface changes in the other class

Accessors, Mutators and Immutable Classes


Self Check

  1. Is the substring method of the String class an accessor or a mutator?
  2. Is the Rectangle class immutable?

Answers

  1. 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
  2. No–translate is a mutator

Side Effects

Side Effects


Self Check

  1. If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect?
  2. Consider the DataSet class of Chapter 7. Suppose we add a method
    void read(Scanner in)
    {
    while (in.hasNextDouble())
    add(in.nextDouble());
    }
    Does this method have a side effect?

Answers

  1. No–a side effect of a method is any change outside the implicit parameter
  2. Yes–the method affects the state of the Scanner parameter

Common Error: Trying to Modify Primitive Type Parameters

Modifying a Numeric Parameter has No Effect on Caller


Call by Value and Call by Reference

Call by Value Example

harrysChecking.transfer(500, savingsAccount);
 

Preconditions

Preconditions

Preconditions

Syntax 9.1: Assertion

 
assert condition;

Example:

 
assert amount >= 0;

Purpose:

To assert that a condition is fulfilled. If assertion checking is enabled and the condition is false, an assertion error is thrown.

Postconditions


Self Check

  1. Why might you want to add a precondition to a method that you provide for other programmers?
  2. 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?

Answers

  1. Then you don't have to worry about checking for invalid values–it becomes the caller's responsibility
  2. No–you can take any action that is convenient for you

Static Methods


Self Check

  1. Suppose Java had no static methods. Then all methods of the Math class would be instance methods. How would you compute the square root of x?
  2. Harry turns in his homework assignment, a program that plays tic-tac-toe. His solution consists of a single class with many static methods. Why is this not an object-oriented solution?

Answers

  1. Math m = new Math();
    y = m.sqrt(x);
  2. In an object-oriented solution, the main method would construct objects of classes Game, Player, and the like. Most methods would be instance methods that depend on the state of these objects.

Static Fields

Static Fields

A Static Field and Instance Fields


Self Check

  1. Name two static fields of the System class.
  2. 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 fields static. Then main can call the other static methods, and all of them can access the static fields. Will Harry's plan work? Is it a good idea?

Answers

  1. System.in and System.out
  2. Yes, it works. Static methods can access static fields 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.

Scope of Local Variables

Scope of Local Variables

Scope of Class Members

Overlapping Scope


Self Check

  1. Consider the deposit method of the BankAccount class. What is the scope of the variables amount and newBalance?
  2. What is the scope of the balance field of the BankAccount class?

Answers

  1. The scope of amount is the entire deposit method. The scope of newBalance starts at the point at which the variable is defined and extends to the end of the method.
  2. It starts at the beginning of the class and ends at the end of the class.

Organizing Related Classes into Packages

Organizing Related Classes into Packages

Package
Purpose
Sample Class
java.lang
Language support
Math
java.util
Utilities
Random
java.io
Input and output
PrintStream
java.awt
Abstract Windowing Toolkit
Color
java.applet
Applets
Applet
java.net
Networking
Socket
java.sql
Database Access
ResultSet
javax.swing
Swing user interface
JButton
org.omg.CORBA
Common Object Request Broker Architecture
IntHolder

Syntax 9.2: Package Specification

 
package packageName;

Example:

 
package com.horstmann.bigjava;

Purpose:

To declare that all classes in this file belong to a particular package

Importing Packages

Package Names and Locating Classes

Base Directories and Subdirectories for Packages


Self Check

  1. Which of the following are packages?
    1. java
    2. java.lang
    3. java.util
    4. java.lang.Math
  2. Can you write a Java program without ever using import statements?
  3. Suppose your homework assignments are located in the directory /home/me/cs101 (c:\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?

Answers

    1. No
    2. Yes
    3. Yes
    4. No
  1. Yes–if you use fully qualified names for all classes, such as java.util.Random and java.awt.Rectangle
  2. /home/me/cs101/hw1/problem1 or, on Windows, c:\me\cs101\hw1\problem1

The Explosive Growth of Personal Computers