Name (print) ____ Ron Cytron ___________________   Lab Section you attend__ All _______

CSE131 Quiz 4 Solution

Each of the 6 responses is worth 15 points

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  "Candidate with " + tally + " votes";   // anything will do here
   }

   public int getTally() {
      return  tally;
   }

   /**
     * Increases the tally by the specified amount
     */
   public void incrTally(int amount) {
      tally = tally + amount; // or similar
   }
}
  1. The above class has stubs. Fill in the implementations to do something reasonable.
  2. How many instance variables does the class declare?   2
  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
    2. What is printed by the above code?
      Tallys are 200 and 100