Object Oriented Design: Building A Fraction Class: Fundamentals of Computer Science
Object Oriented Design: Building A Fraction Class: Fundamentals of Computer Science
http://www.zazzle.com/fraction+tshirts
Fraction class
Create a class to represent fractions
Hey objects, where did you come from?
"Dude, don't you know where objects
come from?!? The object stork totally
dropped us off."
0.1, 0.9,
0.5 0.6
r=0.1 r=0.15
0.5, 0.3
r=0.2
4
Creating with Default Constructor
5
Declaring Your Own Constructor
6
Creating with Default Constructor
public class FractionClient
{
public static void main(String [] args)
{
Fraction a = new Fraction();
% javac FractionClient.java
We broke all the calls to create FractionClient.java:5: error: constructor
a Fraction object since there Fraction in class Fraction cannot be
applied to given types;
no longer exists a no-arg Fraction a = new Fraction();
version of the constructor. ^
required: int,int
found: no arguments
reason: actual and formal argument lists
differ in length
7
Constructor Overloading
Fraction c = a.multiply(b);
...
Fraction c = a.multiply(b);
12
Multiplying Fractions
13
Lowest Terms
Attempt 3: Add code to reduce to lowest terms
public class Fraction
{
...
public Fraction multiply(Fraction other)
{
Fraction result = new Fraction(num * other.num,
denom * other.denom);
int i = Math.min(Math.abs(result.num),
Math.abs(result.denom));
if (i == 0)
return result;
while ((result.num % i != 0) || (result.denom % i != 0))
i--;
Fraction result2 = new Fraction(result.num / i,
result.denom / i);
return result2;
}
% java FractionClient
}
1/2 * 2/3 = 1/3
14
Divide Method
Objects
No-arg default constructors
Fraction object
Built an object to represent a fraction