In: Computer Science
Define a class called Counter whose internal "count" variable is a basic integer counter. This class track that count from its instantiation in the constructor (can be set to any positive integer, or 0). The count should never be allowed to be negative. Include methods that will set the counter to 0, increase the count by 1, and decrease the count by 1.
Include an accessor method that returns the current count value (getCount()). There should be no input / setter method or other mutator methods. The only method that can set the counter is the one that sets it to zero (and the constructor).
This class should also override the Object class toString() and equals() methods - refer to the Java APIs for more guidance on how to override this (Chapter 8 also describes this in a little detail, but the API may be more useful): https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html Finally, write a main method (in this class) to test all the methods in your class definition.
Program Code Screenshot :


Sample Output :

Program Code to Copy
class Counter {
int count;
//Argumented constructor
Counter(int count) {
this.count = count;
}
//Accessor
public int getCount(){
return this.count;
}
//Increment and decremenet
void increment() {
this.count++;
}
void decrement() {
if (this.count > 0)
this.count--;
}
//Reset count to 0
void reset() {
this.count = 0;
}
@Override
public String toString(){
return "(Count : "+this.count+")";
}
@Override
public boolean equals(Object obj){
Counter c = (Counter) obj;
return this.count == c.count;
}
}
class Main {
public static void main(String[] args) {
Counter c = new Counter(5);
System.out.println(c);
c.increment();
c.increment();
System.out.println(c);
Counter d = new Counter(8);
d.decrement();
System.out.println(c+" == "+d+" : "+c.equals(d));
c.reset();
System.out.println("C reset. Count is "+c);
}
}