(a) In the slides and textbook, one of the examples features a class for countin
ID: 3784597 • Letter: #
Question
(a)
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();
}
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.
Your answer should include only the class you have written.
(b)
(Assume the integer-based Counter class in the book also implements the IncrementCounter interface.)
From the perspective of someone choosing to use AnotherCounter versus Counter in a larger program, is there a difference? Explain. Consider both a functionality standpoint, and a performance standpoint.
Explanation / Answer
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();
}
class AnotherCounter implements IncrementCounter
{
String id;
int c;
AnotherCounter(String i)
{
id=i;
c=0;
}
public void increment()
{
c++;
}
public int tally()
{
return c;
}
public String toString()
{
return "ID "+id+" counter "+c;
}
public static void main(String[] args) {
AnotherCounter a=new AnotherCounter("A");
a.increment();
System.out.println(a);
}
}
=======================================
akshay@akshay-Inspiron-3537:~$ javac AnotherCounter.java
akshay@akshay-Inspiron-3537:~$ java AnotherCounter
ID A counter 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.