Q1. [15 pts] A class C is defined with:

  • an instance method void inst()
  • a method static int stat()
  • an instance variable data of type int
  • Inside the body of inst, it is impossible to have the statement "inst();"

    FALSE -- this is the very definition of a recursive invocation

    Inside the body of stat, it is impossible to have the statement "data = 20;"

    TRUE -- a static variable cannot access the instance variable  data

    Inside the body of stat, it is impossible to have the statement "inst();"

    TRUE -- a static method cannot directly invoke an instance method

    Inside the body of inst, it is impossible to have the statement "data = new Integer(17);"

    FALSE -- through the magic of Boxing/Unboxing


    Q2. [20 pts]
    These questions focus on Object-oriented Concepts:

  • Can a Java class have any number of derived classes? If yes, why is this useful?

    YES. A Java class can become the BASE class for any number of derived classes. This is useful because it enables designers to create any number of classes that extend the BASE class in different ways; this capability is the essence of inheritance
     

  • Can a derived class override an inherited method and redefine its return type? If yes, why is this useful?

    As we have described in class, the answer is NO. For example, if a BASE class Student defines a method "int getIdentifier()" but a DERIVED class UndergraduateStudent wishes to refine this as "String getIdentifier()" then when late-binding occurs, the compiler will not know which one is being invoked.

    NOTE that there is a small caveat here that advanced students might have detected. In JDK 1.5 and above, it is acceptable (indeed it is NECESSARY at times) to enable the derived class to redefine the return type of a method to one of its derived subclasses.  Thus, for example, you could have
    Student define a method Object getSchedule() and then the class UndergraduateStudent could redefine to return "SpecialSchedule getSchedule()" since SpecialSchedule is a specialized derived class of java.lang.Object.

     

  • Can a constructor be declared to throw a checked exception? If yes, why is this useful?

    YES. This feature makes it possible to prevent illegal objects from even being created in the first place. The alternative is to System.exit(0) within the constructor when given bad data (a bad option) or to just ignore the bad parameter values and instantiate a default object anyway (a bad option too).
     
  • Can an interface declare a static method for use by its implementing classes? If yes, why is this useful?

    NO. This might sound like a good idea, because the static method could be used by all implementing classes; yet, the context within which the static method would execute varies based upon the implementing class, so this idea is dead to begin with.

  • Q3. [2 pts.] The Dilbert Zone. Extra points if I laugh so hard that milk comes out of my nose. (I've added the Best one so far)

    Q4. [15 pts]. Given an ArrayList object that contains String values, complete the implementation of the following method using the Iterator provided by the ArrayList.

    /**
    * Return String "[value1,value2,value3, ..., valueN]" representing a comma-
    * separated String of the values found in an ArrayList. Note that the String
    * starts with "[", ends with "]", and there is no "," after the nth value.
    */
    public static String format (ArrayList al) {

      Iterator it = al.iterator(); +2 Creating an iterator from ArrayList
      String ret = "["; +1 Starting String with '['
    +1 Using a variable to contain the computed String
      while (it.hasNext()) { +2 Using a While loop/for Loop
    +2 Using the hasNext() method to determine whether to complete
         ret += (String) it.next(); +2 Retrieving next value from the Iterator
         if (it.hasNext()) {
            ret += ",";
         }
    +1 Adding comma between values
    +1 Using some logic to ensure no comma after last one
      }    
      return ret + "]"; +2 For returning the String value
    +1 For terminating String with a ']'
    } 15 TOTAL POINTS

    Q5. [25 pts] You are given the now familiar NumberList and NumberNode classes below:

    /** List of numbers. */
    public class NumberList {
    NumberNode head;  /* first one. */


    /** Prepend NumberNode with i to list. */

    public void add (int i) { … }

    }

    /** Node class representing an integer. */
    public class NumberNode {
      int
              value;    /* node value. */
      NumberNode   next;     /* next one. */

      public NumberNode (int i) {
        value = i;
        next = null;
      }
    }
     


    Write the appropriate equals method in NumberList, which determines if two NumberList entities are equivalent, namely, that the nodes within the two lists contain the same values in the exact same order.

    public boolean equals (Object o) +2 public boolean equals
    +1 Use of Object o instead of NumberList
      if (o == null) { return false; } +2 Detect null case and handle specially
      if (o instanceof NumberList) { +2 Only continue within if we have right class
         NumberList other = (NumberList) o; +2 Cast value into NumberList so we can process
        NumberNode me = head;
        NumberNode him = other.head
    +2 Start with our head value
    +2 Start with other's head value
        while (me != null && him != null) { +1 While Loop or For Loop
    +2 Know to check both for null status
           if (me.value != him.value) { return false; } +2 Use of if to compare me.value [NOT JUST me != him]
    +1 For returning false
           him = him.next;
           me = me.next;
    +2 Advance both pointers synchronously
        }
        return (me == him);
    +2 This nifty code returns true if the lengths of the individual lists were the same (that is, none left over. Could have said: return (me == null && him == null)
      }
       return false;
    }
    +2 Don't forget return false when object o is not a NumberList.
     25 TOTAL

    Q5. [25 pts] This Question was the Afternoon's Question: Assume you have the following classes that represent small polygons of n points, defined by an array of up to ten Points.

    /** Represents a polygon */
    public class Polygon
    {
      /** Space for up to 10 points. */
      Point []points = new Point[10];


      /** Number of actual points. */
      int numPoints = 0;

      /** append point to array. */
      public void add (Point p) {
        points[numPoints] = p;
        numPoints++;
      }

    /** Represents a point in the polygon */
    public class Point {

      int x; /** x-coordinate of point. */
      int y; /** y-coordinate of point. */

      /** Returns distance from this Point to Point p. */
      public double distance (Point p) {

      return Math.sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
     
    }
    }


    Write a method to compute the perimeter of a Polygon as follows. A Polygon with

  • less than two points has perimeter of zero;
  • two points has a perimeter equal to the length of the line segment defined by these points
  • greater than two points has a perimeter equal to the sum of the individual line lengths [p0,p1], [p1,p2], ..., [pn-2,pn-1],[pn-1,p0]
  • public double getPerimeter() +2 public double
    +1 No parameters for method
      if (numPoints < 2) { return 0; } +2 handle small case
      if (numPoints == 2) {
        return points[0].distance(points[1]);
      }
    +2 Handle case where we don't have to worry about trailing final line from pn-1 to p0.
      double perimeter = 0; +2 Use variable for ongoing computation
      for (int i = 0; i < numPoints - 1; i++) {
     
    +2 For Loop involved (or while )
    +2 Initialize Loop properly
    +2 Terminate loop properly (note -1)
    +1 Advance properly
        perimeter += points[i].distance(points[i+1]); +2 Update perimeter
    +2 Compute proper line distance
      }
      perimeter += points[0].distance(points[numPoints-1]);
    +2 Update perimeter to have last line
    +2 Compute proper line distance
      return perimeter; +2 return proper value
      26 TOTAL (of course, no more than 25 assigned!)

    Q6. [25 pts.] You have been hired as a consultant to prepare an initial object oriented design for a project that aims to create a personal weekly planner for scheduled meetings:

    A personal weekly planner can store meetings during an ordinary five-day (Monday-Friday) business week. Some meetings occupy a single time slot (i.e., Tuesday at 11:00 AM) while a multi-day meeting represents a set of time slots throughout the week (i.e., Monday-Tuesday-Thursday-Friday at 11:00 AM). Each meeting has a room location. A time slot consists of a starting time and an ending time. It must be impossible to add to the weekly planner a meeting whose time slot(s) conflict with an existing meeting in the planner.

    (a) [20 pts.] Show your object-oriented design below with boxes representing classes (both operations and data) and show the relationships between your classes

    . One possible design arrangement. Note that there is no Day class. All that is required is for Planner to know of a set of Meetings. There are two types of meetings -- Single Day or MultiDay. Each of these is responsible for knowing their individual relationship with TimeSlot.

    The meeting has a location, which is common across any type of meeting. The conflicts(Meeting m) method is to be overridden by the concrete SingleDay and MultiDay classes. Thus Meeting is an abstract class.

    TimeSlot offers the base capability of knowing whether two timeslots actually conflict. It isn't enough to search for equality. Note that timeslots 10:00 through 1:00 PM conflicts with 11:00 AM through 12:00 PM.

    There are alternate approaches that you could have used.

     

    Point BreakDown:

    Having TimeSlot class to represent slot on the schedule +2
    Having Planner class to oversee everything +2
    Having Meeting class to represent an event on the schedule +2
    having the ability to differentiate between Single Day and Meeting +2
    Having the ability to differentiate between Multi-Day and Meeting +2
    Making sure conflicting schedules don't get created; separate logic spread throughout the classes +3
    Attributes for TimeSlot [start, end] +2
    Attribute Location for Meeting +1
    Capture 1::* relationship between Planner and meetings +2
    Capture 1::1 relationship between singleDay and Timeslot; and capture 1::* relationship between multiDay and Timeslot +2
    TOTAL +20

    (b) [5 pts.] Without showing any code, explain how your planner prevents the addition of conflicting meetings

    One can add a meeting in the Planner, and he will search through his set of known Meetings to know if it conflicts with any existing meetings. To make this work, the Planner iterates over all of its Meeting objects and sees if the new meeting object conflicts with any existing meeting object. This request is delegated, ultimately, to the timeslots for the meeting, where the low-level logic can handle all special cases.