Week 3 & 4 - Object Oriented Design
Week 3 & 4 - Object Oriented Design
Object-Oriented Design
John Lewis
William Loftus
– creating a design
result = Math.sqrt(25)
• See SloganCounter.java
• See Slogan.java
//-----------------------------------------------------------------
// 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
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
A semicolon immediately
follows each method header
// etc.
}
Copyright © 2012 Pearson Education, Inc.
Interfaces implements is a
reserved word
// etc.
}
Copyright © 2012 Pearson Education, Inc.
Doable AliCanDo VeliCanDo
ody
b
o
N !!
N: ds!
T IO ho
E N et
T T em
A r th
fo
//-----------------------------------------------------------------
// 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;
}
ody
b
//-----------------------------------------------------------------
// Returns the question. N:
T IO
//-----------------------------------------------------------------
public String getQuestion() E N
{ T T re!
A he
return question; is
}
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());
}
}
str3 = str1.concat(str2);
//-----------------------------------------------------------------
// 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;
}
}
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 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;
}
}
//-----------------------------------------------------------------
// 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;
}
}
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,
Address jHome = new AddressOH("21
44132
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.
Aggregation in UML
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
PigLatin
PigLatinTranslator
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") );
}
}
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"));
}
}
PigLatin
PigLatinTranslator
• See ParameterTester.java
• See ParameterModifier.java
• See Num.java
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 + "";
}
}
float tryMe(int x)
{
Invocation
return x + .375;
} 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);