- Consider
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());
}
- [Draw picture]
- General rules for constructors:
- Same name as class
- No return type
- Can execute any code, but rare to do much more than set private
variables
- Suppose we have a second counter:
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());
}
- What happens if assign a and b to same thing?
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());
}
- draw picture
- What happens to the bananas?