- Forward


Developing Classes
With Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • What is a set?
    • A finite or infinite collection of unique elements/members (in which order may or may not have significance)
    • Expand
  • How are sets defined?
    • Extension - Listing all of the elements/members
      (e.g., \(S = \{1, 3, 5\}\))
    • Intension - Describing the properties of the elements/members
      (e.g., \(T = \{t: 0 \leq t \leq 10\}\))
    • Expand
Classes
Back SMYC Forward
  • Definition:
    • A definition of a set that is written in terms of the properties of the elements/members (i.e., an intensive definition of a set)
    • The set of elements/members so defined
  • What is an object?
    • An element/member of the set
  • Encapsulation:
    • (v) The process of defining an entity in terms of its characteristics
    • (n) A result of the encapsulation process
The Design and Implementation of Classes
Back SMYC Forward
  • What is involved in designing and implementing a class?
    • Creating an intensive definition (i.e., a list of attributes and behaviors)
  • What is involved in designing and implementing the attributes?
    • Declaring the names and types of instance variables
    • Declaring the names and types of class variables
  • What is involved in designing and implementing the behaviors?
    • Declaring the signatures of instance and class methods
    • Implementing the bodies of instance and class methods
Steps in the Process
Back SMYC Forward
  1. Create an initial encapsulation
  2. Refine the encapsulation
  3. Identify constructors
  4. Think about the need for private methods
  5. Identify helpful overloaded methods
  6. Identify class attributes
  7. Identify class behaviors
What's the Starting Point?
Back SMYC Forward
  • When Things are Simple:
    • A brief textual description (i.e., a paragraph or two), written by a single person, that contains a discussion of what needs to be remembered about the entity and what the entity needs to be able to do.
  • In Most Situations:
    • Possibly conflicting lists of needs and desires from all of the stakeholders. (More on this when you study software engineering.)
What's the Starting Point? (cont.)
Back SMYC Forward

An Example of a Textual Description

A picture frame is used to display a picture. It always has a width and height (measured in inches). It may or may not have a matte/border (also measured in inches). If it has a matte, it is the same size on all four sides. One can calculate the visible area of a picture frame from its area and the area of the matte.

A picture frame may or may not have a stand.

One can calculate the cost of a picture frame from the amount of material used in the perimeter of the frame itself and the area of the glass.

Creating the Initial Encapsulation
Back SMYC Forward
  • Instance Attributes/Fields:
    • Identify the noun phrases in the description
    • Think about the data types to use for each noun phrase
  • Instance Behaviors/Methods:
    • Identify the verb phrases in the description
    • Think about the parameters for each verb phrase
Creating the Initial Encapsulation (cont.)
Back SMYC Forward
  1. Make all instance attributes private
  2. Provide "get" methods (called accessors) where needed
  3. Provide "set" methods (one type of mutator) methods where needed
Creating the Initial Encapsulation (cont.)
Back SMYC Forward

An Example

A picture frame is used to display a picture. It always has a width and height (measured in inches). It may or may not have a matte/border (also measured in inches). If it has a matte, it is the same size on all four sides. One can calculate the visible area of a picture frame from its area and the area of the matte.

A picture frame may or may not have a stand.

One can calculate the cost of a picture frame from the amount of material used in the perimeter of the frame itself and the area of the glass.

Creating the Initial Encapsulation (cont.)
Back SMYC Forward

An Example

public class PictureFrame { private double width; private double height; private double matte; private boolean stand; private boolean hasMatte; public double calculateVisibleArea(){return 0.0;} public double calculateCost(){return 0.0;} }
Refining the Encapsulation: Attributes
Back SMYC Forward
  • Local Variables:
    • Should be used whenever possible
    • Remember that local variables can be passed between methods
  • Instance Attributes:
    • Should be essential to the definition of the class
    • Should define the "state" of the objects in the class
    • Should not be redundant
Refining the Encapsulation: Attributes (cont.)
Back SMYC Forward

Overuse of Instance Attributes

javaexamples/oopbasics/Screen.java
 
Refining the Encapsulation: Attributes (cont.)
Back SMYC Forward

Eliminating a Redundancy

public class PictureFrame { private double width; private double height; private double matte; // 0.0 when there is no matte private boolean stand; public double calculateCost(){return 0.0;} public double calculateVisibleArea(){return 0.0;} }
Refining the Encapsulation: Behaviors
Back SMYC Forward
  • Look for Similar Behaviors:
    • Do they just handle positive/negative numbers differently?
    • Do they just handle upper/lower case differently?
  • Look for Missing Behaviors:
    • Have multiple behaviors been rolled into one?
    • Most classes should have a "to string" behavior
    • Most classes should have an "equals" behavior
Refining the Encapsulation
Back SMYC Forward

Adding equals() and toString() Methods

public class PictureFrame { private double width; private double height; private double matte; // 0.0 when there is no matte private boolean stand; public double calculateCost(){return 0.0;} public double calculateVisibleArea(){return 0.0;} public boolean equals(PictureFrame other) {return false); public String toString(){return "";} }
Identifying Constructors
Back SMYC Forward
  • Purpose:
    • Initialization that need to be performed when an object is created
  • Syntax:
    • Have no return type and the same name as the class
Identifying Constructors (cont.)
Back SMYC Forward

An Example

javaexamples/oopbasics/pictureframe/start/PictureFrame.java
 
Identifying Constructors (cont.)
Back SMYC Forward
  • Overloaded Constructors:
    • Multiple constructors with different parameters
  • Terminology:
    • The default constructor has no parameters and assigns default values to the parameters
    • The copy constructor has a parameter of the same type as the object being constructed and makes a (deep) copy of its parameters
    • All other are called explicit value constructors
Overloaded Constructors (cont.)
Back SMYC Forward
  • Reducing Code Duplication:
    • Constructors can call other methods
    • Constructors can call other constructors using this() provided the calls are made in the first statement
  • Automatic Constructor in Java:
    • A default constructor is created by Java if no constructor is provided
    • If any constructor is provided then you must explicitly include a default constructor if you want to have one
Overloaded Constructors (cont.)
Back SMYC Forward

Adding Copy, Default, and Explicit Value Constructors

javaexamples/oopbasics/pictureframe/overloadedconstructors/PictureFrame.java (Fragment: Constructors)
 
Overloaded Constructors (cont.)
Back SMYC Forward

A Common Mistake

public PictureFrame(double width, double height, double matte, boolean stand) { double h, w; h = Math.abs(height); w = Math.abs(width); this.width = Math.min(w, h); this.height = Math.max(w, h); this.matte = Math.abs(matte); this.stand = stand; } public PictureFrame(double width, double height) { PictureFrame frame; frame = new PictureFrame(width, height, 0.0, false); }
More on Copy Constructors
Back SMYC Forward
  • Copy Constructors are Particularly Important for Mutable Objects:
    • Aliases are not very dangerous when working with immutable objects
  • A Common Convention:
    • The clone() method creates a shallow copy
    • The copy constructor creates a deep copy
More on Copy Constructors (cont.)
Back SMYC Forward

In this example, since both of the attributes are primitive types, the distinction between shallow and deep copies does not arise.

javaexamples/basics/Pair.java (Fragment: CopyConstructor)
 

If, for example, the Pair class included a String attribute named id, then a shallow copy would include the statement:

this.id = other.id; // this.id is an alias for other.id

whereas a deep copy would include the statement:

this.id = new String(other.id); // Use the copy constructor in String
Identifying Useful Private Methods
Back SMYC Forward
  • Defined:
    • A private method can not be used by objects of another class or called by functions outside of the class in which it is defined
  • What Use Are They?
    • They generally act as "helpers"
Private Methods (cont.)
Back SMYC Forward
javaexamples/oopbasics/pictureframe/privatemethods/PictureFrame.java
 
Identifying Helpful Overloaded Methods
Back SMYC Forward
  • Definition:
    • Two or more methods with the same name but different signatures in the same class
  • Implementation in Java:
    • Must have different parameters (number and/or type)
    • Must have the same return type
Overloaded Methods: An Example
Back SMYC Forward
javaexamples/oopbasics/pictureframe/overloadedmethods/PictureFrame.java (Fragment: overloadedmethods)
 
Overloaded Methods: Common Uses
Back SMYC Forward
  • Handling Default Values
  • Different Similar Types
  • Two Parameters and Many "Parameters"
Overloaded Methods: Default Handling
Back SMYC Forward
  • Observation:
    • Sometimes we want a method to use default values and sometimes we want to supply all of the parameters
  • Solution:
    • Have two methods with the same name and different numbers of parameters
Overloaded Methods: Default Handling (cont.)
Back SMYC Forward

An Example

public class TaxStand { . . . /** * Calculates the tax payment based on income and * filing status */ public double payment(int income, int status) { ... } /** * Calculates the tax payment assuming the * filing status is 0 */ public double payment(int income) { return payment(income, 0); } }
Overloaded Methods: Similar Types
Back SMYC Forward
  • Observation:
    • Sometimes we want to perform the same operation on different, but similar, types (e.g., int and double)
  • Solution:
    • Have two methods with the same name and different types of parameters
Overloaded Methods: Similar Types (cont.)
Back SMYC Forward

An Example

public class Weight { . . . /** * Change this Weight by a given amount * * @param amount The amount of the change */ public void changeBy(Weight amount) { ... } /** * Change this Weight by a given amount * * @param pounds Number of pounds in the change * @param ounces Number of ounces in the change * @param positive true to increase, false to decrease */ public void changeBy(int pounds, int ounces, boolean positive) { ... } }
Overloaded Methods: Similar Types (cont.)
Back SMYC Forward

An Example

public class TaxStand { . . . /** * Calculates the tax payment based on income and * filing status */ public double payment(int income, int status) { ... } /** * Calculates the tax payment based on income and * filing status */ public double payment(double income, int status) { ... } }
Overloaded Methods: Similar Types (cont.)
Back SMYC Forward
  • Observation:
    • Calling a function with a similar type might be handled by automatic type conversion.
  • In Java:
    • The compiler attempts to use overloading before it attempts to use automatic type conversion
    • If multiple methods are appropriate, the compiler uses the "most specific" version
Overloaded Methods: Cardinality
Back SMYC Forward
  • Observation:
    • Sometimes we want to perform the same operation on two and "more than two" values
  • Solution:
    • Have two methods, one with two parameters and one with an array as the parameter
Overloaded Methods: Cardinality (cont.)
Back SMYC Forward

An Example

public int minimum(int a, int b) { int min; min = a; if (b < a) min = b; return b; } public int minimum(int[] values) { int min; min = values[0]; for (i=1; i < values.length; i++) { if (values[i] < min) min = values[i]; } return min; }
Identifying Class Attributes
Back SMYC Forward
  • Definition:
    • Attributes that belong to a class (or all of its instances) rather than individual instances of a class
  • Implication:
    • They can be used without instantiating an object
  • Java:
    • Must be declared static
Class Attributes: Common Uses
Back SMYC Forward
  • Constants, flags and special values
  • Common values (across all instances)
  • Object counters
Class Attributes: Constants etc...
Back SMYC Forward
  • In the Integer Class:
    • MIN_VALUE
    • MAX_VALUE
  • In the Double Class:
    • NEGATIVE_INFINITY
    • POSITIVE_INFINITY
    • MIN_VALUE
    • MAX_VALUE
  • In the Math Class:
    • E (base of the natural log)
    • PI
Class Attributes: Constants etc... (cont.)
Back SMYC Forward
javaexamples/oopbasics/pictureframe/staticattributes/PictureFrame.java (Fragment: staticattributes)
 
Class Attributes: Common Values
Back SMYC Forward

An Example

public class ProgressiveSlotMachine { // Attributes of the class private static double jackpot; // Attributes of objects private double currentBet; . . . private void handleLosingSpin() { jackpot = jackpot + 0.5 * currentBet; } }
Class Attributes: Object Counters
Back SMYC Forward

An Example

/** * A user account */ public class UserAccount { // Attributes of the class private static int nextAccountNumber; // Attributes of objects protected final int accountNumber; protected String name; /** * Explicit Value Constructor * * @param name The name of the account holder */ public UserAccount(String name) { // Store the name this.name = name; // Store the account number accountNumber = nextAccountNumber; // Setup the account number for the next account nextAccountNumber++; }
Identifying Class Methods
Back SMYC Forward
  • Definition:
    • Methods that belong to a class rather than instances of a class
  • Implication:
    • They can be used without instantiating an object
  • Java:
    • Must be declared static
Class Methods: Common Uses
Back SMYC Forward
  • Utility classes
  • System calls
  • "Factory" methods
Class Methods: Utility Classes
Back SMYC Forward
  • Definition:
    • A class that groups related functionality and is not "data types"
  • The Math Class:
    • abs
    • sin
    • cos
    • tan
    • log
    • pow
    • sqrt
Class Methods: System Calls
Back SMYC Forward
  • In the System Class:
    • currentTimeMillis
    • exit
Class Methods: "Factory" Methods
Back SMYC Forward
  • Definition:
    • Methods that are used like constructors
  • Observations:
    • May get an object from a "pool"
    • Must be static to avoid a chicken and egg problem
    • Are much more flexible than constructors because they have an explicit return statement
  • Examples:
    • Double.parseDouble(java.lang.String) java.lang.Double#parseDouble(java.lang.String)
    • Integer.parseInt(java.lang.String) java.lang.Integer#parseInt(java.lang.String)
    • NumberFormat.getInstance() java.text.NumberFormat#getInstance()
Class Methods: "Factory" Methods (cont.)
Back SMYC Forward

A parsePictureFrame() Method in the PictureFrame Class

javaexamples/oopbasics/pictureframe/factories/PictureFrame.java (Fragment: parse)
 
"Factory" Methods vs. Constructors
Back SMYC Forward
  • A Question:
    • Why not write a constructor instead?
  • Some Answers (Which May Make More Sense Later):
    • It's useful to have an explicit return (e.g., to return a special value like null, to return a specialization, to return a realization, to return a remote object)
    • There are pre-defined objects in the class (e.g., a singleton, an object pool)
    • The object can't be fully initialized
There's Always More to Learn
Back -