We will defined a Counter
object!
int
Finish and test the implementation!
public class Counter {
private int count;
// constructor defines how to initialize instance
public Counter () {
count = 0;
}
// getter method for count
public int getCount () {
return count;
}
// increment the counter
public void increment () {
count++;
}
// reset the counter
public void reset () {
count = 0;
}
}
Create an instance of the Counter
class:
// create a Counter instance
Counter myCounter = new Counter();
// increment the counter: call instance method
myCounter.increment();
// print the current count
System.out.println("Current count: " + myCounter.getCount());
Counter
Class?Couldn’t we have just used an int
?
Counter
is Preferable to int
Counter
signals object is being used to count something
int
could signify anything!Counter
restricts the operations
Counter
objects without knowledge of internal workingsCounter
Given any positive integer $a$, we have
Writing the multiplication as repeated addition, we get
What does Java think of this?
Consider the following piece of code
int a = 10;
double recip = 1.0 / a;
double product = 0;
// add 1/a to itself a times
for (int i = 0; i < a; i++) {
product += recip;
}
product
to be?product
?What happened?
Why?
Does it matter?
Now consider an execution of the following code:
double one = product;
int iter = 50;
for (int i = 0; i < iter; i++) {
one = one * one;
}
power
to be?power
?Our calculations that should all give a value of 1
But can give values arbitrarily far from 1
float
and double
) in binaryHow can we ensure that we have, for example,
Increasing the precision of float
and double
won’t fix the problem!
Design a Fraction
object to represent fractional values!
+
and *
)?Fraction
?We’ll write and test our Fraction
class!