Ryerson University
School of Computer Science
CPS209 Term Test #1(D) : Winter 2006
Worth = 15%; Time limit = 50 minutes; No aids

Name:____________________________________ Student #: ______________________

Note: there are several meanings of the word interface, but in this exam the only meaning that applies is the java construct of which Comparable is a typical example.
A. (1 point each)
  1. Polymorphism. Recall that java.util.Arrays class has a method public static void sort(Object[] a) which sorts array a in ascending order, assuming all elements of the array implement the Comparable interface. Modify the following class so that Porcupine objects can be sorted by this method in increasing number of quills.
    public class Porcupine
    {
       private int quills ;
       public Porcupine(int initialQuills) { quills = initialQuills ; }
    
    
    
    }
    
  2. Inner class. Consider this top-level and inner class. Circle which variables can the method function access:
    a    b    c    d    e    f    g    h
     public class Outer
    {
       private int h ;
       public void method(final int f, int g)
       {
          int e ;
          final int d ;
          class Inner implements I
          {
              public void function()
              { 
                 ...
              }
          }
          int c ;
          final int b ;
          ...
       }
       private int a ;
    }
    
  3. Interface. Suppose classes A and B both implement interfaces X and Y. Indicate whether each of the following blocks considered in isolation will (a) work without error, (b) have a compilation error or (c) have a runtime error.
  4. Inner class: Give two kinds of variables an inner class can access from a top-level class, not counting static variables.
  5. drawing: Write a panel's paintComponent which draws a green-filled ellipse (width 30, height 20) with a vertical black line (length 20) touching it in one spot on the right side.
              public void paintComponent(Graphics g)
              {
                  Graphics2D g2 = (Graphics) g ;
    
                  ______________________________________
    
                  ______________________________________
    
                  ______________________________________
              }
    

B. (2 points) Write an interface Countable that has one boolean method canVote with no parameters.

C. (3 points) Write a method public static int countVoters(Object[] x) which counts the number of voters in the array. Each element of the array must implement Countable.

D. (5 points) Write a class ColorChanger which is a mouse listener inside class PressPanel which extends JPanel. Assume the class is an inner class, inside the constructor of PressPanel (but only write the inner class, not code from the outer class). As the mouse is pressed, the color cycles from Color.RED, to Color.GREEN to Color.BLUE and back to Color.RED, etc.. Use the setBackground(color) method.