Name (print) ___________________________________   Lab Section you attend______________

CSE131 Quiz 4
Encapsulation
26 Sept 2008

Solution
Consider the following Java class:
public class Candidate {
   private int tally;
   private String name;
   public Candidate(String name) {
      this.name = name;
      tally     = 0;
   }
   public String toString() {
      return  "";   // stub, fill in real code below:


   }

   public int getTally() {
      return 0;     // stub, fill in real code below:

   }

   /**
     * Increases the tally by the specified amount
     */
   public void incrTally(int amount) {
      // stub, fill in real code below:

   }
}
  1. The above class has stubs. Fill in the implementations to do something reasonable.
  2. How many instance variables does the class declare?
    
    
  3. Consider the code:
      Candidate d = new Candidate("Barack Obama");
      Candidate r = new Candidate("John McCain");
      d.incrTally(100);
      r.incrTally(d.getTally());
      d.incrTally(r.getTally());
      System.out.println("Tallys are " + d.getTally() + " and " + r.getTally());
    
    1. How many Candidate objects are instantiated by the above code?
    2. What is printed by the above code?