Lecture 08: Objects and Memory

Overview

1. Finishing and Testing Fraction
2. Objects and Memory

Last Time

We started writing a Fraction class to represent fractional values

public class Fraction {
private long num; // numerator
private long den; // denominator

public Fraction (long numerator, long denominator) {
num = numerator;
den = denominator;
}

// Fraction g, Fraction h then g.add(h) returns "g + h"
public Fraction add (Fraction f) {

// (a / b) + (c / d) = (a * d + b * c) / b * d
long newNum = num * f.den + den * f.num;
long newDen = den * f.den;

return new Fraction(newNum, newDen);
}

// compute the greatest common divisor of two longs
public static long gcd (long a, long b) {
if (b == 0) {
return a;
}

return gcd(b, a % b);
}
}

Today

Improving and testing the implementation

1. Storing fractions as reduced fractions
2. Converting to other formats:
• double
• String
3. Comparing with BadArithmetic from last week

Conclusion

We can design objects that do better arithmetic!

Objects and Memory

A Question

What does the following code do?

int a = 10;
int b = 5;

b = a;

a = 20;

What are the values of a and b at the end of the execution?

Second Question

Consider the method

void setValue (int a, int value) {
a = value;
}

What is the result of

a = 20;
setValue(a, 0);

What is the value of a at the end of the execution?

Again, but with objects

Consider the following simple class

class Number {
public int value;

Number (int val) {
value = val;
}
}

First Question, again

What does the following code do?

Number aNum = new Number(10);
Number bNum = new Number(5);

bNum = aNum;
aNum.value = 20;

What are the values of a and b at the end of the execution?

Second Question, again

Consider the method

void setNumberValue (Number a, int value) {
a.value = value;
}

What is the result of

setNumberValue(aNum, 0);

What is the value of aNum.value at the end of the execution?