CS365 Midterm -- Spring 2015

Solutions

  1. You may use a one page front-and-back "cheat" sheet for this exam. You may not use a computer or any electronic devices.
  2. You must answer all of the questions.
  3. Answer all the questions on the exam itself and hand in the exam.
  4. You must use Java to implement the coding question.
  5. Good luck!

  1. (14 points: General) For each question below, look at the following list of items and fill in the blank with the best choice.
    package       extends      import            virtual method
    interface     type         namespace         replicated inheritance
    class         Console      final             multiple inheritance
    public        Scanner      const             shared inheritance
    protected     subclasses   static            polymorphism
    composition   inheritance  iterator          abstract class
    friend
    

    1. type A set of values + a set of operations that manipulate those values

    2. friend If you are writing a class in C++, the keyword you would use to indicate that another class is allowed to use your class's protected variables.

    3. interface The Java construct used to declare an abstract type.

    4. composition If I want a square to inherit a rectangle's implementation, but not its interface, I can do so by making the square contain a pointer to a rectangle object and delegating any behavior I wish to inherit from the rectangle by calling the appropriate methods in the rectangle. What is the name of this technique?

    5. shared inheritance Suppose I want class D to multiply inherit from two superclasses, B and C, and that B and C both inherit from A. If I want D to contain only one copy of A, what type of inheritance do I want?

    6. polymorphism A concept that refers to a procedure that performs the same type of action on different types of data.

    7. package The keyword used in Java to declare the module to which a class belongs.

  2. (10 points): General Answer true or false for the following questions.

    1. true Event driven programming differs from procedural programming in that the user, rather than the program, controls what type of input is processed next by the program.

    2. false A subtype is allowed to implement only a proper subset of a type's operations.

    3. true In Java, methods are virtual by default.

    4. true Instance variables that are declared as protected can be accessed by any class within the same package.

    5. false It is permissable to create objects that are instances of an abstract class (i.e., you can call the new operator with an abstract class).

  3. (12 points: Generics) Answer the following questions about C, C++, and Java's generics/template mechanisms:

    1. C++ The language(s) whose generics mechanism allows generics to be instantiated with primitive types, such as int or double.

    2. Java, C The language(s) that allow their generic code to be compiled, since only one copy of the code is required.

    3. Boxing The term used for Java's ability to store primitive types in a generic by automatically converting them to an object of the appropriate type, and on retrieval from the generic, automatically converting them back to the appropriate primitive type.

    4. Java The language(s) that allow the programmer to specify that the type used to instantiate a generic should support a certain API.

    5. If I want to create a generic Box struct in C that stores a single value, how should I declare it? Circle the best answer.
      1. struct Box {
            generic value;
        };
        
      2. struct Box<T>
            T value;
        }
        
      3. struct Box {
            void *value;
        };
        
      4. struct Box {
            void value;
        }
        

  4. (10 points: Inheritance) Answer the following questions about inheritance. For the multiple choice problems circle the best answer.

    1. This type of polymorphism occurs with inheritance hierarchies and allows subclasses to define different implementations for the same method, with the intention that the different method implementations all achieve the same outcome (e.g., draw an object)
      1. parametric polymorphism
      2. generic polymorphism
      3. subtype polymorphism
      4. inheritance polymorphism

    2. How would I declare a pure virtual method in Java?
      1. abstract void draw();
      2. virtual void draw() = 0;
      3. virtual void draw();
      4. void draw() = 0;

    3. What is the output of f.type() and a.type in the following, abbreviated, Java program:
      
      f.type(): apple
      
      a.type(): apple
      
      class fruit {
          void type() { System.out.println("fruit"); }
      
          public static void main(String[] args) {
                fruit f = new apple();
                apple a = new apple();
                f.type();
                a.type();
          }
      }
      
      class apple extends fruit {
          void type() { System.out.println("apple"); }
      }
      
    4. In C++, if I want the subclass Circle to inherit Oval's implementation but not its interface, how should I declare Circle?

      1. class Circle : public Oval { ... };
      2. class Circle extends protected Oval { ... };
      3. class Circle : protected Oval { ... };
      4. class Circle : protected super Oval { ... };
      5. class Circle : protected base Oval { ... };
      6. class Circle : implementation Oval { ... };

    5. Virtual methods are implemented by:
      1. Inlining their method body in the calling procedure
      2. Using a vtable to find the address of the appropriate method body and then jumping to that address to execute the method body.
      3. Following a chain of superclass pointers from the leaf until you find a class object that contains a method with the appropriate name and executing that method's function body.
      4. Searching from the root of the inheritance hierarchy toward the leaf until you find a class object that contains a method with the appropriate name and executing that method's function body.

  5. (13 points: Exception Handling) Answer the following questions about exception handling in C, C++, and Java by circling the best answer.

    1. In C++, suppose I want to throw an array out of bounds exception and I want to pass the subscript as an argument. What is the best way to make the throw?
      1. throw index;

        where index is the integer index that is out-of-range.

      2. throw ArrayOutOfBoundsException(index);

        where ArrayOutOfBoundsException is a class that can store the out-of-bounds index and index is the out-of-bounds index.

      3. throw new ArrayOutOfBoundsException(index);

        where ArrayOutOfBoundsException is a class that can store the out-of-bounds index and index is the out-of-bounds index.

      4. throw exception(index);

        where index is the integer index that is out-of-range.

    2. In C++, I have the following class declarations:
          class StackException;
          class StackLogicException : public StackException;
          class StackRuntimeException : public StackException;
          class StackEmptyException : public StackRuntimeException;
          class StackLengthException : public StackLogic Exception;
      
      and the following throw statement:
          throw StackLengthException();
      
      Which of the following catch clauses can catch this exception? Circle all that apply.
      1. catch (StackException)
      2. catch (StackLogicException)
      3. catch (StackRuntimeException)
      4. catch (StackEmptyException)
      5. catch (StackLengthException)
      6. catch (StackLengthException *)
      7. catch(std::exception)
      8. catch(...)
      9. catch(default)
      10. catch(StackLengthException &)

    3. Suppose you have the following general construction in Java:
      ... assign some value to x ...
      try {
         if (x < 10)
              throw new Exception();
      }
      catch ...
      catch ...
      finally { ... }
      
      Under what conditions would the finally clause execute? Circle all conditions that apply.
      1. When the try block completes successfully without throwing the Exception object
      2. When the try block throws the Exception object and one of the catch clauses catches and handles it
      3. When the try block throws the Exception object, one of the catch clauses catches and handles it, and then rethrows it.
      4. When the try block throws the Exception object up the call chain because none of the catch clauses handle it.

    4. What is the pre-defined Java base class for creating programmer-defined exceptions that will be checked by the compiler (i.e., the compiler will require the throwing function to either handle the exception or declare that it is throwing it out of the function)?
      1. Error
      2. Exception
      3. Throwable
      4. RuntimeException

  6. (10 points: Event Handling) For each question below, look at the following list of items and fill in the blank with the best choice(s).
    BorderLayout               BoxLayout             GridLayout
    FlowLayout                 GridBagLayout         text box              
    slider                     menu                  command buttons
    radio buttons              check boxes           content pane
    JFrame                     JPanel                JComponent
    Adapters                   Listeners             Delegators
    Command Objects            Generators            JContainer
    

    1. text box The type of widget I should use to allow a user to enter a 5 digit zip code.

    2. BoxLayout The layout manager that allows a programmer to position objects either vertical or horizontally and that allows the user to use invisible "spacer" objects, such as glue objects and rigid area objects, to control the spacing of objects.

    3. GridBagLayout The layout manager that I might use to layout a dialog box that is roughly organized as a grid but which requires different row and column sizes, and which also requires some widget groups to span multiple rows or columns.

    4. Listeners The general name given to the Java objects which are added to widgets in order to be notified of and to handle events generated by these widgets.

    5. check boxes The widget you should use to allow a user to select any of the following 6 toppings for their burrito: cheese, onions, olives, guacamole, sour cream, salsa. The user is allowed to select as many of these toppings as they wish (i.e., they are not mutually exclusive).

  7. (10 points): Object-Oriented Programming Your manager has asked you to take over a botched Java project in which three different programmers produced three different classes to handle a menu widget for the Mac, Windows, and X window systems. The problem is that each programmer created an inheritance hierarchy for their window system, so the MacMenu class inherits from Mac, the WindowsMenu class inherits from Windows, and the XMenu class inherits from X. At least enough process control was exercised so that the Mac, Windows, and X programmers all chose getChoice as their method for accessing the currently selected menu item. Your product is about to ship and it is supposed to support all three platforms but you do not want your users to worry about what type of menu they have created after the initial creation of the menu. You want the user to be able to say something like:

      
    Menu FileMenu = (winSystem == MAC ? new MacMenu : 
                    (winSystem == WINDOWS ? new WindowsMenu : 
                                            new XMenu));
    ...
    String selection = FileMenu.getChoice();
    

    Right now the user will not be able to do that. Instead the user will have to write code that looks like:

    MacMenu = (winSystem == MAC ? new MacMenu : null);
    WindowsMenu = (winSystem == WINDOWS ? new WindowsMenu : null);
    XMenu = (winSystem == X ? new XMenu : null);
      ...
    String selection = (winSystem == MAC) ? MacMenu.getChoice()
                : ((winSystem == WINDOWS) ? WindowsMenu.getChoice();
                : XMenu.getChoice());
    
    How can you arrange to quickly correct this problem and allow the product to ship on time? You are not allowed to changed the inheritance hierarchy because that would be too time-consuming. Clearly you must declare a new data type called Menu and you will have to modify the three classes. Show the class/interface declarations that you must write or modify.

    Define an interface called Menu that contains a getChoice method and then change each of the class declarations so that they implement the interface. Nothing else in the classes needs to be modified because the getChoice method is already defined.

    public interface Menu {
        public String getChoice();
    }
    
    class WindowsMenu extends WindowsWidget implements Menu { ... }
    class MacMenu extends MacWidget implements Menu { ... }
    class XMenu extends XWidget implements Menu { ... }
    

  8. (3 points: Executing a Java Program) Assume that: Write the full java command required to execute the PrintScores program that you write in question 9.
    java -classpath /home/Users bvz.PrintScores < gradefile
    
  9. Write a program named PrintScores.java that reads student scores and for each student outputs the maximum student score. The program should be placed in a package named bvz.
    package bvz;
    
    import java.util.*;
    
    class PrintScores {
        PrintScores() {
    	Scanner console = new Scanner(System.in);
    	int maxScore; 
    	int score;
    	while (console.hasNextInt()) {
    	    maxScore = console.nextInt();
    	    while (console.hasNextInt()) {
    		score = console.nextInt();
    		if (score > maxScore)
    		    maxScore = score;
    	    }
    	    // I accepted printf as well
    	    System.out.format("%s %d%n", console.next(), maxScore);
    	}
        }
        public static void main(String[] args) {
    	new PrintScores();
        }
    }