08 - Chapter 7 - Object-Oriented Design
08 - Chapter 7 - Object-Oriented Design
08 - Chapter 7 - Object-Oriented Design
Object-Oriented Design
John Lewis
William Loftus
creating a design
Divide et Impera
8
Design
A software design specifies how a program will
accomplish its requirements
A software design specifies how the solution can be
broken down into manageable pieces and what
each piece will do
An object-oriented design determines which
classes and objects are needed, and specifies
how they will interact
Low level design details include how individual
methods will accomplish their tasks
Copyright 2012 Pearson Education, Inc.
MOBAS Architecture
Implementation
Implementation is the process of translating a
design into source code
Objects are stored in memory and are reclaimed by the garbage collector
when they are no longer referenced or when a Java program terminates. It
is desirable, however, to be able to save any given object for future use.
This trait is called persistence, and the ability to do this is by saving the
instance data of the object to a file.
Copyright 2012 Pearson Education, Inc.
Quiz
In which phase of program development would you
expect the programmer(s) to create the pseudocode
(e.g. a flowchart of the main algorithm)?
A) Software requirements
B) Software design
C) Software implementation
D) Software testing
E) Could occur in any of the above
See SloganCounter.java
See Slogan.java
continue
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
//-----------------------------------------------------------------
// Constructor: Sets up the slogan and counts the number of
// instances created.
//-----------------------------------------------------------------
public Slogan (String str)
{
phrase = str;
count++;
}
continue
//-----------------------------------------------------------------
// Returns this slogan as a string.
//-----------------------------------------------------------------
public String toString()
{
return phrase;
}
//-----------------------------------------------------------------
// Returns the number of instances of this class that have been
// created.
//-----------------------------------------------------------------
public static int getCount ()
{
return count;
}
}
continue
if (r1.isLike(r2))
System.out.println ("r1 and r2 are equal.");
else
System.out.println ("r1 and r2 are NOT equal.");
r3 = r1.reciprocal();
System.out.println ("The reciprocal of r1 is: " + r3);
r4 = r1.add(r2);
r5 = r1.subtract(r2);
r6 = r1.multiply(r2);
r7 = r1.divide(r2);
//-----------------------------------------------------------------
// Constructor: Sets up the rational number by ensuring a nonzero
// denominator and making only the numerator signed.
//-----------------------------------------------------------------
public RationalNumber (int numer, int denom)
{
if (denom == 0)
denom = 1;
continue
numerator = numer;
denominator = denom;
reduce();
}
//-----------------------------------------------------------------
// Returns the numerator of this rational number.
//-----------------------------------------------------------------
public int getNumerator ()
{
return numerator;
}
//-----------------------------------------------------------------
// Returns the denominator of this rational number.
//-----------------------------------------------------------------
public int getDenominator ()
{
return denominator;
}
continue
//-----------------------------------------------------------------
// Returns the reciprocal of this rational number.
//-----------------------------------------------------------------
public RationalNumber reciprocal ()
{
return new RationalNumber (denominator, numerator);
}
//-----------------------------------------------------------------
// 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;
continue
//-----------------------------------------------------------------
// Subtracts the rational number passed as a parameter from this
// rational number.
//-----------------------------------------------------------------
public RationalNumber subtract (RationalNumber op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int difference = numerator1 - numerator2;
//-----------------------------------------------------------------
// Multiplies this rational number by the one passed as a
// parameter.
//-----------------------------------------------------------------
public RationalNumber multiply (RationalNumber op2)
{
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();
continue
Copyright 2012 Pearson Education, Inc.
continue
//-----------------------------------------------------------------
// Divides this rational number by the one passed as a parameter
// by multiplying by the reciprocal of the second rational.
//-----------------------------------------------------------------
public RationalNumber divide (RationalNumber op2)
{
return multiply (op2.reciprocal());
}
//-----------------------------------------------------------------
// Determines if this rational number is equal to the one passed
// as a parameter. Assumes they are both reduced.
//-----------------------------------------------------------------
public boolean isLike (RationalNumber op2)
{
return ( numerator == op2.getNumerator() &&
denominator == op2.getDenominator() );
}
continue
//-----------------------------------------------------------------
// Returns this rational number as a string.
//-----------------------------------------------------------------
public String toString ()
{
String result;
if (numerator == 0)
result = "0";
else
if (denominator == 1)
result = numerator + "";
else
result = numerator + "/" + denominator;
return result;
}
continue
//-----------------------------------------------------------------
// Reduces this rational number by dividing both the numerator
// and the denominator by their greatest common divisor.
//-----------------------------------------------------------------
private void reduce ()
{
if (numerator != 0)
{
int common = gcd (Math.abs(numerator), denominator);
continue
//-----------------------------------------------------------------
// Computes and returns the greatest common divisor of the two
// positive parameters. Uses Euclid's algorithm.
//-----------------------------------------------------------------
private int gcd (int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return num1;
}
}
false
a /= b
true
true false
a>b
a=a-b b=b-a
return a
Quiz
Rewrite the toString() method of the class
RationalNumber using the conditional operator
System.out.println (john);
System.out.println ();
System.out.println (marsha);
}
}
Copyright 2012 Pearson Education, Inc.
Output
//********************************************************************
// StudentBody.java Author: Lewis/Loftus
// John Smith
// Demonstrates the use of an
Home aggregate class.
Address:
//********************************************************************
21 Jump Street
Lynchburg, VA 24551
public class StudentBody
{ School Address:
800 Lancaster Ave.
//-----------------------------------------------------------------
Villanova,
// Creates some Address PA objects
and Student 19085 and prints them.
//-----------------------------------------------------------------
public static void main (String[]
Marsha Jones args)
{
Home Address:
Address school = new Address ("800 Lancaster Ave.", "Villanova",
123 Main Street
"PA", 19085);
Euclid, OH
Address jHome = new Address ("2144132
Jump Street", "Lynchburg",
School Address:
"VA", 24551);
800
Student john = new Lancaster
Student Ave.
("John", "Smith", jHome, school);
Villanova, PA 19085
Address mHome = new Address ("123 Main Street", "Euclid", "OH",
44132);
Student marsha = new Student ("Marsha", "Jones", mHome, school);
System.out.println (john);
System.out.println ();
System.out.println (marsha);
}
}
Copyright 2012 Pearson Education, Inc.
//********************************************************************
// Student.java Author: Lewis/Loftus
//
// Represents a college student.
//********************************************************************
//-----------------------------------------------------------------
// Constructor: Sets up this student with the specified values.
//-----------------------------------------------------------------
public Student (String first, String last, Address home,
Address school)
{
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
}
continue
//-----------------------------------------------------------------
// Returns a string description of this Student object.
//-----------------------------------------------------------------
public String toString()
{
String result;
return result;
}
}
//-----------------------------------------------------------------
// Constructor: Sets up this address with the specified data.
//-----------------------------------------------------------------
public Address (String street, String town, String st, long zip)
{
streetAddress = street;
city = town;
state = st;
zipCode = zip;
}
continue
//-----------------------------------------------------------------
// Returns a description of this Address object.
//-----------------------------------------------------------------
public String toString()
{
String result;
return result;
}
}
StudentBody Student
- firstName : String
+ main (args : String[]) : void - lastName : String
- homeAddress : Address
- schoolAddress : Address
+ toString() : String
Address
- streetAddress : String
- city : String
- state : String
- zipCode : long
+ toString() : String
A semicolon immediately
follows each method header
// etc.
}
//-----------------------------------------------------------------
// Constructor: Sets up the question with a default complexity.
//-----------------------------------------------------------------
public Question (String query, String result)
{
question = query;
answer = result;
complexityLevel = 1;
}
continue
//-----------------------------------------------------------------
// Sets the complexity level for this question.
//-----------------------------------------------------------------
public void setComplexity (int level)
{
complexityLevel = level;
}
//-----------------------------------------------------------------
// Returns the complexity level for this question.
//-----------------------------------------------------------------
public int getComplexity()
{
return complexityLevel;
}
//-----------------------------------------------------------------
// Returns the question.
//-----------------------------------------------------------------
public String getQuestion()
{
return question;
}
continue
//-----------------------------------------------------------------
// Returns the answer to this question.
//-----------------------------------------------------------------
public String getAnswer()
{
return answer;
}
//-----------------------------------------------------------------
// Returns true if the candidate answer matches the answer.
//-----------------------------------------------------------------
public boolean answerCorrect (String candidateAnswer)
{
return answer.equals(candidateAnswer);
}
//-----------------------------------------------------------------
// Returns this question (and its answer) as a string.
//-----------------------------------------------------------------
public String toString()
{
return question + "\n" + answer;
}
}
import java.util.Scanner;
continue
Copyright 2012 Pearson Education, Inc.
continue
System.out.print (q1.getQuestion());
System.out.println (" (Level: " + q1.getComplexity() + ")");
possible = scan.nextLine();
if (q1.answerCorrect(possible))
System.out.println ("Correct");
else
System.out.println ("No, the answer is " + q1.getAnswer());
System.out.println();
System.out.print (q2.getQuestion());
System.out.println (" (Level: " + q2.getComplexity() + ")");
possible = scan.nextLine();
if (q2.answerCorrect(possible))
System.out.println ("Correct");
else
System.out.println ("No, the answer is " + q2.getAnswer());
}
}
continue
//-----------------------------------------------------------------
// Constructor: Sets up each value with an associated string.
//-----------------------------------------------------------------
Season (String months)
{
span = months;
}
//-----------------------------------------------------------------
// Returns the span message for this value.
//-----------------------------------------------------------------
public String getSpan()
{
return span;
}
}
String name;
int rank;
int numStudents;
}
Outline
Software Development Activities
Identifying Classes and Objects
Static Variables and Methods
Class Relationships
Interfaces
Enumerated Types Revisited
Method Design
Testing
GUI Design and Layout
PigLatin
PigLatinTranslator
import java.util.Scanner;
continue
do
{
System.out.println ();
System.out.println ("Enter a sentence (no punctuation):");
sentence = scan.nextLine();
System.out.println ();
result = PigLatinTranslator.translate (sentence);
System.out.println ("That sentence in Pig Latin is:");
System.out.println (result);
System.out.println ();
System.out.print ("Translate another sentence (y/n)? ");
another = scan.nextLine();
}
while (another.equalsIgnoreCase("y"));
}
}
import java.util.Scanner;
sentence = sentence.toLowerCase();
while (scan.hasNext())
{
result += translateWord (scan.next());
result += " ";
}
continue
Copyright 2012 Pearson Education, Inc.
continue
return result;
}
//-----------------------------------------------------------------
// Translates one word into Pig Latin. If the word begins with a
// vowel, the suffix "yay" is appended to the word. Otherwise,
// the first letter or two are moved to the end of the word,
// and "ay" is appended.
//-----------------------------------------------------------------
private static String translateWord (String word)
{
String result = "";
if (beginsWithVowel(word))
result = word + "yay";
else
if (beginsWithBlend(word))
result = word.substring(2) + word.substring(0,2) + "ay";
else
result = word.substring(1) + word.charAt(0) + "ay";
return result;
}
continue
//-----------------------------------------------------------------
// Determines if the specified word begins with a vowel.
//-----------------------------------------------------------------
private static boolean beginsWithVowel (String word)
{
String vowels = "aeiou";
continue
//-----------------------------------------------------------------
// Determines if the specified word begins with a particular
// two-character consonant blend.
//-----------------------------------------------------------------
private static boolean beginsWithBlend (String word)
{
return ( word.startsWith ("bl") || word.startsWith ("sc") ||
word.startsWith ("br") || word.startsWith ("sh") ||
word.startsWith ("ch") || word.startsWith ("sk") ||
word.startsWith ("cl") || word.startsWith ("sl") ||
word.startsWith ("cr") || word.startsWith ("sn") ||
word.startsWith ("dr") || word.startsWith ("sm") ||
word.startsWith ("dw") || word.startsWith ("sp") ||
word.startsWith ("fl") || word.startsWith ("sq") ||
word.startsWith ("fr") || word.startsWith ("st") ||
word.startsWith ("gl") || word.startsWith ("sw") ||
word.startsWith ("gr") || word.startsWith ("th") ||
word.startsWith ("kl") || word.startsWith ("tr") ||
word.startsWith ("ph") || word.startsWith ("tw") ||
word.startsWith ("pl") || word.startsWith ("wh") ||
word.startsWith ("pr") || word.startsWith ("wr") );
}
}
int a1 = 111;
Num a2 = new Num (222);
Num a3 = new Num (333);
continue
f1 = 999;
f2.setValue(888);
f3 = new Num (777);
//-----------------------------------------------------------------
// Sets up the new Num object, storing an initial value.
//-----------------------------------------------------------------
public Num (int update)
{
value = update;
}
continue
//-----------------------------------------------------------------
// Sets the stored value to the newly specified value.
//-----------------------------------------------------------------
public void setValue (int update)
{
value = update;
}
//-----------------------------------------------------------------
// Returns the stored integer value as a string.
//-----------------------------------------------------------------
public String toString ()
{
return value + "";
}
}
What is printed?
What is printed?
Circle: x = 1; y = 1; r = 4
Copyright 2012 Pearson Education, Inc.
Method Overloading
Let's look at one more important method design
issue: method overloading
Method overloading is the process of giving a
single method name multiple definitions in a
class
If a method is overloaded, the method name is not
sufficient to determine which method is being called
The signature of a method is: the number, type,
and order of the parameters
The signature of each overloaded method must be
unique
Copyright 2012 Pearson Education, Inc.
Method Overloading
The compiler determines which method is being
invoked by analyzing the parameters
float tryMe(int x)
{
return x + .375; Invocation
} result = tryMe(25, 4.32)
and so on...
The following lines invoke different versions of the
println method:
System.out.println ("The total is:");
System.out.println (total);
A) specification
B) design
C) implementation
D) testing
E) maintenance
A) specification
B) design
C) implementation
D) testing
E) maintenance
Software requires modification (such as new requirements
such as new features or I/O specifications) and so the
maintenance phase is on-going whereas the other phases end
once the software has been released and is in use.
Quiz
Modifying a program in order to eliminate deficiencies
is done in the ________ phase of the development
cycle.
A) design
B) implementation
C) testing
D) use
E) maintenance
2 7 6
9 5 1
4 3 8
Users
Know the User
Knowing the user implies an understanding of:
the user's true needs
the user's common activities
the user's level of expertise in the problem domain
and in computer processing
Possible
user's
requests
Flow Layout
Border Layout
Card Layout Defined in the AWT
Grid Layout
GridBag Layout
Box Layout Defined in Swing
Overlay Layout
java tutorial
Layout Managers
Every container has a default layout manager, but
we can explicitly set the layout manager as well
import javax.swing.*;
continue
frame.getContentPane().add(tp);
frame.pack();
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
add (l1);
add (l2);
}
}
import java.awt.*;
import javax.swing.*;
add (l1);
add (l2);
}
}
import java.awt.*;
import javax.swing.*;
setBackground (Color.green);
continue
add (b1);
add (b2);
add (b3);
add (b4);
add (b5);
}
}
add (b1);
add (b2);
add (b3);
add (b4);
add (b5);
}
}
North
South
import java.awt.*;
import javax.swing.*;
setBackground (Color.green);
continue
import java.awt.*;
import javax.swing.*;
setBackground (Color.green);
continue
add (b1);
add (b2);
add (b3);
add (b4);
add (b5);
}
}
add (b1);
add (b2);
add (b3);
add (b4);
add (b5);
}
}
See BoxPanel.java
Copyright 2012 Pearson Education, Inc.
//********************************************************************
// BoxPanel.java Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the box layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
setBackground (Color.green);
continue
add (b1);
add (Box.createRigidArea (new Dimension (0, 10)));
add (b2);
add (Box.createVerticalGlue());
add (b3);
add (b4);
add (Box.createRigidArea (new Dimension (0, 20)));
add (b5);
}
}
add (b1);
add (Box.createRigidArea (new Dimension (0, 10)));
add (b2);
add (Box.createVerticalGlue());
add (b3);
add (b4);
add (Box.createRigidArea (new Dimension (0, 20)));
add (b5);
}
}
A line border
surrounds the component with a simple line
the line's color and thickness can be specified
An etched border
creates the effect of an etched groove around a
component
uses colors for the highlight and shadow
A titled border
places a title on or around the border
the title can be oriented in many ways
A matte border
specifies the sizes of the top, left, bottom, and right edges
of the border separately
uses either a solid color or an image
Copyright 2012 Pearson Education, Inc.
Borders
A compound border
is a combination of two borders
one or both of the borders can be a compound border
See BorderDemo.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}