8:00 Quiz 3

Statistics:

mean     19.476 (818.000/42)
stddev   4.495
median   20.000
midrange 16.000-22.000

#  avg
1  5.21 / 10
2  4.19 / 5
3 10.07 / 15

Question 3-1

What distinguishes the purpose of a class method from an instance method? That is, how should you decide whether a particular behavior should be an instance method or a class method? (I am not asking how they are syntactically distinguished in Java. The syntactic distinction is that a class method includes a static keyword in its declaration, while an instance method does not.)

Question 3-2

Name Java's seven primitive types other than boolean. For each, specify whether the type requires 8 bits, 16 bits, 32 bits, or 64 bits.

Question 3-3

Define a Counter class to represent simple counting devices. It should include the following methods.

Counter()
(Constructor method) Constructs a counter holding the initial value 0.

void increment()
Adds one to the value represented by the counter.

int getValue()
Returns the current value represented by the counter.

The following run() method illustrates the use of the Counter type you are to define.
public static void run() {
    Counter a = new Counter();
    Counter b = new Counter();
    a.increment();
    IO.println(a.getValue());     // prints ``1''
    a.increment();
    b.increment();
    IO.println(a.getValue());     // prints ``2''
    IO.println(b.getValue());     // prints ``1''
}
Write your answer below.
public class Counter {

    // : (your code here)

}

Solutions

Solution 3-1

An instance method is a behavior that applies to specific objects of a class, while a class method is a behavior that applies to the class as a whole. When you call an instance method, you must apply it to a particular object (e.g., file.readInt(), where file is an InputFile object); but a class method can be applied to the entire class (e.g., IO.readInt(), which uses the readInt() class method in the IO class).

Solution 3-2

byte8
short16
int32
long64
float32
double64
char16

Solution 3-3

public class Counter {
    private int val;

    public Counter() {
        val = 0;
    }

    public void increment() {
        val++;
    }

    public int getValue() {
        return val;
    }
}