Part A(I have solution for this, need help with Part B) In the slides and textbo
ID: 3784820 • Letter: P
Question
Part A(I have solution for this, need help with Part B)
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.
I have answer for this as below:
But another question is Part B and "I need help with Part B only"
Part 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.
my solution for Part A
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);
}
}
Explanation / Answer
PartB
1. Counter class
2. AnotherCounter that implements IncrementCounter
Yes, there is a difference. If you user IncrementCounter as counter then programmer has flexibility to use different
implementation of IncrementCounter(many logic of counting).
We can reference of any class that implements IncrementCounter
Ex:
AnotherCounter1 implements IncrementCounter{
}
AnotherCounter2 implements IncrementCounter{
}
IncrementCounter counter = // object of any class that implements IncrementCounter (run time polymorphism)
But if you user Counter class then later you can not have option to provide differen logic of counting