Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the slides and textbook, one of the examples features a class for counting up

ID: 3880936 • Letter: I

Question

In the slides and textbook, one of the examples features a class for counting up. An interface which defines this functionality is given below:

public interface IncrementCounter {

      //Increments the counter by one.

      void increment();

      //Returns the number of increments since creation.

      int tally();

      //Returns a string representation that counts number of increments and the ID of the counter.

      String toString();

}

Use java to write a class that implements this interface while not using any number type member variables (e.g., int, float, etc). The class should be named AnotherCounter and have a constructor that takes a String parameter to store as an ID.

Explanation / Answer

//Interface

public interface IncrementCounter {
      void increment();
      int tally();
      String toString();
}

//Implementation class

public class AnotherCounter implements IncrementCounter{
   private String id;
   private String inc="0";
   public AnotherCounter() {
      
   }
   public AnotherCounter(String id) {
       this.id=id;
   }
   @Override
   public void increment() {
       id = Integer.toString(Integer.parseInt(id)+1);
       inc = Integer.toString(Integer.parseInt(inc)+1);
   }
   @Override
   public int tally() {
      
       return Integer.parseInt(inc);
   }
   public String toString() {
       return "Number of increment :"+inc+" counter id :"+id;
   }
}

//Test class

public class Test {

   public static void main(String[] args) {
       AnotherCounter anotherCounter = new AnotherCounter("10");
       anotherCounter.increment();
       anotherCounter.increment();
       int id = anotherCounter.tally();
       System.out.println("Number of Increment "+id);
       System.out.println(anotherCounter);
   }

}