• Now we can extend our discussion of the design of classes and objects• Chapter 7 focuses on: – software development activities – determining the classes and objects that are needed for
Trang 1Chapter 7 Object-Oriented Design
Java Software Solutions
Foundations of Program Design
Seventh Edition
John Lewis William Loftus
Trang 2• Now we can extend our discussion of the design of classes and objects
• Chapter 7 focuses on:
– software development activities
– determining the classes and objects that are needed for a program – the relationships that can exist among classes
– the static modifier
– writing interfaces
– the design of enumerated type classes
– method design and method overloading
– GUI design and layout managers
Trang 3Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 4• The creation of software involves four basic
activities:
– establishing the requirements
– creating a design
– implementing the code
– testing the implementation
and interact
Trang 5• Software requirements specify the tasks that a
program must accomplish
– what to do, not how to do it
they should be critiqued and expanded
complete requirements
significant time and expense in the overall project
Trang 6• A software design specifies how a program will
accomplish its requirements
broken down into manageable pieces and what
each piece will do
classes and objects are needed, and specifies how they will interact
methods will accomplish their tasks
Trang 7• Implementation is the process of translating a
design into source code
the heart of software development, but actually it
should be the least creative step
requirements and design stages
including style guidelines and documentation
Trang 8• Testing attempts to ensure that the program will
solve the intended problem under all the constraints specified in the requirements
goal of finding errors
• Debugging is the process of determining the cause
of a problem and fixing it
this chapter
Trang 9Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 10• The core activity of object-oriented design is
determining the classes and objects that will make
up the solution
from a previous project, or newly written
the objects discussed in the requirements
an object provides are generally verbs
Trang 11Identifying Classes and Objects
or object in the final solution
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log The
summary report of all transactions must be structured
as specified in section 7.A.
Trang 12• Remember that a class represents a group
(classification) of objects with the same behaviors
given names that are singular nouns
as needed
Trang 13Identifying Classes and Objects
something should be represented as a class
represented as a set of instance variables or as an Address object
the more clear these issues become
be decomposed into multiple smaller classes to
distribute the responsibilities
Trang 14• We want to define classes with the proper amount
of detail
separate classes for each type of appliance in a
house
Appliance class with appropriate instance data
solved
Trang 15Identifying Classes and Objects
process of assigning responsibilities to each class
be represented by one or more methods in one or more classes
every method of every class – begin with primary responsibilities and evolve the design
Trang 16Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 17Static Class Members
invoked through its class name
static:
result = Math.sqrt(25)
• Variables can be static as well
• Determining if a method or variable should be static
is an important design decision
Trang 18• We declare static methods and variables using the static modifier
rather than with an object of that class
methods and static variables are sometimes called class variables
Trang 19Static Variables
a variable is declared as static, only one copy of
the variable exists
private static float price;
• Memory space for a static variable is created when the class is first referenced
• All objects instantiated from the class share its
static variables
• Changing the value of a static variable in one
object changes it for all others
Trang 20• Because it is declared as static, the cube method can be invoked through the class name:
Trang 21Static Class Members
by convention visibility modifiers come first
by the Java interpreter without creating an object
because instance variables don't exist until an
object exists
variables or local variables
Trang 22• Static methods and static variables often work
together
Slogan objects have been created using a static variable, and makes that information available
using a static method
Trang 23// objects that were created.
Trang 25obj = new Slogan ("Live Free or Die.");
Remember the Alamo.
Don't Worry Be Happy.
Live Free or Die.
Talk is Cheap.
Write Once, Run Anywhere.
Slogans created: 5
Trang 26// Represents a single slogan string.
//********************************************************************
public class Slogan
{
private String phrase;
private static int count = 0;
Trang 28Why can't a static method reference an instance
variable?
Trang 29You don't need an object to execute a static method.
And even if you had an object, which object's instance
data would be referenced? (remember, the method is
invoked through the class name)
Trang 30Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 31Class Relationships
types of relationships to each other
– Dependency: A uses B
– Aggregation: A has-a B
– Inheritance: A is-a B
Trang 32• A dependency exists when one class relies on
another in some way, usually by invoking the
methods of the other
Trang 33same class
same class as a parameter
class takes as a parameter another String object
str3 = str1.concat(str2);
Trang 34• The following example defines a class called
RationalNumber
represented as the ratio of two integers
accept another RationalNumber object as a
parameter
Trang 35// operations on them.
public static void main (String[] args)
{
RationalNumber r1 = new RationalNumber (6, 8);
RationalNumber r2 = new RationalNumber (1, 3);
RationalNumber r3, r4, r5, r6, r7;
System.out.println ("First rational number: " + r1);
System.out.println ("Second rational number: " + r2);
continue
Trang 36System.out.println ("r1 and r2 are equal.");
Trang 37The reciprocal of r1 is: 4/3 r1 + r2: 13/12
r1 - r2: 5/12 r1 * r2: 1/4 r1 / r2: 9/4
Trang 38// Represents one rational number with a numerator and denominator.
// Constructor: Sets up the rational number by ensuring a nonzero
// denominator and making only the numerator signed.
Trang 40// Returns the reciprocal of this rational number.
// Adds this rational number to the one passed as a parameter.
// A common denominator is found by multiplying the individual
// denominators.
public RationalNumber add (RationalNumber op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int sum = numerator1 + numerator2;
return new RationalNumber (sum, commonDenominator);
}
continue
Trang 41int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int difference = numerator1 - numerator2;
return new RationalNumber (difference, commonDenominator);
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();
return new RationalNumber (numer, denom);
}
continue
Trang 42// Divides this rational number by the one passed as a parameter
// by multiplying by the reciprocal of the second rational.
// Determines if this rational number is equal to the one passed
// as a parameter Assumes they are both reduced.
Trang 44// Reduces this rational number by dividing both the numerator
// and the denominator by their greatest common divisor.
int common = gcd (Math.abs(numerator), denominator);
numerator = numerator / common;
denominator = denominator / common;
}
}
continue
Trang 45
// Computes and returns the greatest common divisor of the two
// positive parameters Uses Euclid's algorithm.
Trang 46• An aggregate is an object that is made up of other
objects
objects as instance data
relies on the objects that compose it
Trang 47composed, in part, of Address objects
two addresses)
Trang 48// Demonstrates the use of an aggregate class.
//********************************************************************
public class StudentBody
{
// Creates some Address and Student objects and prints them.
public static void main (String[] args)
Student john = new Student ("John", "Smith", jHome, school);
Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132);
Student marsha = new Student ("Marsha", "Jones", mHome, school);
Trang 49// StudentBody.java Author: Lewis/Loftus
Student john = new Student ("John", "Smith", jHome, school);
Address mHome = new Address ("123 Main Street", "Euclid", "OH",
21 Jump Street Lynchburg, VA 24551 School Address:
800 Lancaster Ave.
Villanova, PA 19085
Marsha Jones Home Address:
123 Main Street Euclid, OH 44132 School Address:
800 Lancaster Ave.
Villanova, PA 19085
Trang 50// Represents a college student.
//********************************************************************
public class Student
{
private String firstName, lastName;
private Address homeAddress, schoolAddress;
Trang 51result = firstName + " " + lastName + "\n";
result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress;
return result;
}
}
Trang 52// Represents a street address.
//********************************************************************
public class Address
{
private String streetAddress, city, state;
private long zipCode;
Trang 54- schoolAddress : Address
+ toString() : String
- streetAddress : String
- city : String
- state : String
- zipCode : long
Address
Trang 55The this Reference
refers to the object through which the method is
being executed
method called tryMe, which is invoked as follows:
obj1.tryMe();
obj2.tryMe();
obj1; in the second it refers to obj2
Trang 56• The this reference can be used to distinguish the instance variables of a class from corresponding
method parameters with the same names
4 could have been written as follows:
public Account (String name, long acctNumber,
double balance)
{
this name = name;
this acctNumber = acctNumber;
this balance = balance;
}
Trang 57Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 58• A Java interface is a collection of abstract methods
and constants
method body
modifier abstract, but because all methods in an interface are abstract, usually it is left off
that a class will implement
Trang 59public interface Doable
{
public void doThis();
public int doThat();
public void doThis2 ( double value, char ch);
public boolean doTheOther (int num);
}
A semicolon immediately follows each method header
None of the methods in
an interface are given
a definition (body) interface is a reserved word
Trang 60• An interface cannot be instantiated
default
method in the interface
must define all methods in the interface
Trang 61Each method listed
in Doable is given a definition
Trang 62• In addition to (or instead of) abstract methods, an interface can contain constants
access to all its constants
other methods as well
Trang 63public void setComplexity ( int complexity);
public int getComplexity();
}
Trang 64// Represents a question (and its answer).
//********************************************************************
public class Question implements Complexity
{
private String question, answer;
private int complexityLevel;
Trang 66// Returns the answer to this question.
Trang 67Scanner scan = new Scanner (System.in);
q1 = new Question ("What is the capital of Jamaica?",
"Kingston");
q1.setComplexity (4);
q2 = new Question ("Which is worse, ignorance or apathy?",
"I don't know and I don't care");
q2.setComplexity (10);
continue
Trang 68System.out.println (" (Level: " + q1.getComplexity() + ")");
Trang 70• A class can implement multiple interfaces
interfaces listed in the header
class ManyThings implements interface1, interface2
{
// all methods of both interfaces
}
Trang 71method called compareTo, which is used to
compare two objects
String class in Chapter 5
us the ability to put strings in lexicographic order
Trang 72• Any class can implement Comparable to provide a mechanism for comparing objects of that type
if (obj1.compareTo(obj2) < 0)
System.out.println ("obj1 is less than obj2");
negative is obj1 is less that obj2, 0 if they are
equal, and positive if obj1 is greater than obj2
one object less than another
Trang 73The Iterator Interface
object that provides a means of processing a
collection of objects one at a time
Iterator interface, which contains three methods
– The hasNext method returns a boolean result – true if there are items left to process
– The next method returns the next object in the iteration – The remove method removes the object most recently returned by the next method
Trang 74• Another interface, Iterable, establishes that an object provides an iterator
iterator, that returns an Iterator object
for-each version of the for loop
that perform an iteration; an Iterable object
provides an iterator on request
Trang 75methods (such as compareTo) without formally
implementing the interface (Comparable)
between a class and an interface allows Java to
deal with an object in certain ways
design in Java
Trang 76Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships
Interfaces Enumerated Types Revisited Method Design
Testing GUI Design and Layout
Trang 77Enumerated Types
which define a new data type and list all possible values of that type:
enum Season {winter, spring, summer, fall}
declare variables
Season time;
the ones established in the enum definition
Trang 78• An enumerated type definition is a special kind of class
that type
time = Season.fall;
Trang 79Enumerated Types
interesting than a simple list of values
additional instance data and methods
constructor
Trang 80// Enumerates the values for Season.
//********************************************************************
public enum Season
{
winter ("December through February"),
spring ("March through May"),
summer ("June through August"),
fall ("September through November");
private String span;
continue