public class ItemCounter
{
private int tally = 0; // explicit initialization, though default is 0
private String category;
public void setCategory(String category)
{
this.category = category;
}
public String getCategory()
{
return category;
}
public void increment()
{
tally++;
}
public void decrement()
{
tally--;
}
public int count()
{
return tally;
}
//improvement: initialize during creation
public ItemCounter(String category)
{
this.category = category;
}
}
//....
public static void main(String[] args)
{
ItemCounter a = new ItemCounter();
a.setCategory("apples");
a.increment();
a.increment();
a.increment();
System.out.println("Value of a: " + a.count() + " " + a.getCategory());
}
public static void main(String[] args)
{
ItemCounter a = new ItemCounter("apples");
ItemCounter b = new ItemCounter("bananas");
a.increment();
a.increment();
b.increment();
a.increment();
System.out.println("Value of a: " + a.count() + " " + a.getCategory());
System.out.println("Value of b: " + b.count() + " " + b.getCategory());
}
public static void main(String[] args)
{
ItemCounter a = new ItemCounter("apples");
ItemCounter b = new ItemCounter("bananas");
b = a;
a.increment();
a.increment();
b.increment();
a.increment();
System.out.println("Value of a: " + a.count() + " " + a.getCategory());
System.out.println("Value of b: " + b.count() + " " + b.getCategory());
}
String name = ...
if ( name.equals("Johnny") )
Systtem.out.println("Run!");
public boolean equals(ItemCounter otherCounter)
{
return this.category.equals(otherCounter.getCategory())
&& this.tally == otherCounter.tally;
}
public void steal(ItemCounter otherCounter)
{
this.tally += otherCounter.tally;
otherCounter.tally = 0;
}
public void increment(int amount)
{
tally += amount;
}
public boolean equals(int number)
{
return tally == number;
}
public class ProduceInventory
{
ItemCounter appleCount = new ItemCounter("apples");
ItemCounter pearCount = new ItemCounter("pears");
ItemCounter orangeCount = new ItemCounter("oranges");
ItemCounter mysteryCount = new ItemCounter("unknown");
public void receiveShipment(int apples, int pears,
int oranges, int mysteries)
{
appleCount.increment(apples);
pearCount.increment(pears);
orangeCount.increment(oranges);
mysteryCount.increment(mysteries);
}
public void printInventory()
{
// you write this!
}
}