Write code that defines a class. The class' name shall be Counter
. (Think: what does this imply about the file name? Keep in mind that we will want this to be a public
class so that we can use it for testing.) A Counter
is used to count things (not surprising).
To do this, each instance of the class will contain a "count" value. (Think: what would be a good name for this value? How do we make a separate value for each instance of a class, that belongs to the instances?) The value shall not be negative. (Obvious; how could you have a negative number of things?) You are expected to make sure that the value cannot become negative (this should happen automatically, if you are doing things in remotely normal ways).
The class should provide the following functionality:
A method that sets the count value to 0. (Think: what is a good name for this method? It should be public
of course, since it is part of how other code will use the class. Think: do you need any parameters for this method? If so, what?)
A method that increases the count by 1. (Think: as above.)
A method that decreases the count by 1. (Think: as above. Also, what happens if the count is already 0, given that we must not let it become negative? Decide what to do in this case.)
A method that returns the current count value. (This is called an "accessor").
A method that displays the current count value. (Note: this is a very bad idea design-wise, but your assignment requires it. Hint: use one of the methods of System.out
to output to the screen.)
A method called toString
that returns a String representation of the counter. This should not take any parameters, and must return a String. (This is a standard piece of functionality that most objects in Java provide. Think: other than the count value, is there anything else that ought to be included in the string?)
A method called equals
that compares the Counter to another Counter for equality. This method must take exactly one parameter, a Counter instance, and return a boolean
indicating whether the two Counters are equal. (Think: what determines whether two counters are "equal"?)
The class should NOT provide any of the following functionality:
- Any other method that changes the value of the counter (especially not one that reads a value from standard input).
Write a program that creates some Counter
instances and uses their methods. The program should prove that your Counter
class behaves as expected, by producing output that agrees with what you'd expect from reading the main program. (Hint: since this is Java, we will need another class for this program, with a public static void main(String[] args)
method. Put it in another file. You may need to play around with package
and import
statements so that the main program can find your Counter
class in the other file. Make sure you understand how to compile and run Java classes.)