﻿﻿ CS 1110/1111: Introduction to Programming

Lecture 25

Announcements

Possible mumps case at UVa

Talking Points

Pictures of `this`

Getters and Setters

Write the following class:

Fraction
int numerator
int denominator
Fraction(int n, int d)
double asDouble()

What happens if we do the following?

```Fraction f = new Fraction(2,3);
f.denominator = 0;
double d = f.asDouble();
```

To prevent this we make fields `private` and add getters (also called accessors or inspectors) and setters (also called mutators). The setters can check for bad behavior

```public int getDenominator() {
return this.denominator;
}
public void setDenominator(int denom) {
if (denom != 0) {
this.denominator = denom;
} // else ignore the update request
}
```

What happens if we do the following?

```Fraction f = new Fraction(2,0);
double d = f.asDouble();
```

To prevent this, we use the setters in the constructor too:

```public Fraction(int num, int den) {
// start it in a sane state
this.numerator = 0;
this.denominator = 1;
// then use the setters
this.setNumerator(num);
this.setDenominator(den);
}
```

toString

Every class inherits a few methods from the `Object` class. This includes the method `public String toString()`. This is how a class is printed and added to Strings. But the default version of this gives nonsense.

It is always a good idea to write your own `toString`

```public String toString() {
return this.getNumerator() + "/" + this.getDenominator();
}
```

Then you can do things like

```Fraction f = new Fraction(2, 3);
System.out.println(f + " = " + f.asDouble());
```

Extending Fraction class

We'll add some of the following.

Fraction
int numerator
int denominator
Fraction(int n, int d)
double asDouble()
Fraction plus(Fraction that)
Fraction minus(Fraction that)
Fraction times(Fraction that)
Fraction inverse()
void invert()
void reduce()
boolean lessThan(Fraction that)
boolean lessThan(int that)
boolean lessThan(double that)

Suggested practice: write the rest.

From lecture

Code from 001 (3pm): Fraction.java, TestFraction.java; slides

Code from 002 (1pm): Fraction.java, TestFraction.java; slides