1. CMPSC 221
Object-Oriented Programming with Web Applications
Spring 2011
Exam I: Object-Oriented Programming
February 17, 2011
Name: SOLUTION Last 4 digits of ID: ____ ____ ____ ____
I certify that I have not discussed the contents of the exam with any other student and I will not
discuss the contents of this exam with any student in this class before it is returned to me with a
grade. I have not cheated on this exam in any way, nor do I know of anyone else who has cheated.
Signature: _________________________________________________________
Directions/Notes:
Honor Code Statement
• Write your ID on every page of this exam. Write your name just on this cover page.
• No notes, books, or calculators are permitted.
• Be sure to sign the honor code statement when you are finished.
• Answer each conceptual question completely, clearly, and concisely.
• All questions on this exam are implicitly prefaced with “As taught in CMPSC 221 lectures this
term.”
• In coding problems, you may assume all import statements needed have been provided and you
may always assume you have in scope a properly-initialized Scanner object called input to
read from the console.
• No comments are required in coding problems unless explicitly required. They may be added to
clarify assumptions (as long as assumptions don't circumvent the problems at hand).
• The points intentionally add up to more than 100 possible.
Score Breakdown:
Problem Page 2
Conceptual
Page 3
Conceptual
Problem 1 Problem 2 Problem 3 Total
Score
Value 20 20 5 23 35 100
2. CMPSC 221 / Spring 2011 / Exam 1 - Page 2 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
Part I: Conceptual Questions [40 points]
1. Static members. [6 pts.]
a. What does it mean for a member of a class to be static?
A static member is independent of objects/instances of the class (or it is shared among all instances).
b. Contrast and justify programming practices for initializing static and non-static data members within a class.
Non-static (instance) data members are initialized in constructors. Meanwhile, as static members are independent of
objects, they're initialized in the class data dictionary.
c. Compare and contrast how static and non-static methods are called outside of a class.
Non-static (instance) methods are called using dot notation on the name of an object, whereas static methods are
calling using dot notation on the name of the class.
2. How does composition help facilitate encapsulation? [4 pts.]
Composition is the idea of using classes together (using has-a relationships). If we use several classes to solve a
problem, those classes would naturally be smaller than if we had used one larger class. This facilitates encapsulation, as
the classes created are more focused on more closely related data and behavior. (Encapsulation is keeping related data
and behavior in the same place.)
3. Consider the inheritance hierarchy shown at right. Each part of this question is independent. [10 pts.]
a. In which class(es) would it make most sense to have protected members? Which class(es) would be able to
access those protected members directly?
Since A and C have subclasses, it would make sense for them to have
protected members (as protected members can be accessed directly in the
class where they're created and in subclasses of that class).
The protected members of A could be accessed in A, B, C, D, and E.
The protected members of C could be accessed in C, D, and E.
b. Which class(es) can access private members of class C directly?
Any private members of C could only be accessed in C, as private
members can only be accessed directly in the class which defines them.
A
B C
D E
c. Suppose class C contains an abstract method. Suppose we wish to instantiate objects of this hierarchy. Which
class(es) are or could be abstract and which are concrete?
Since C has an abstract method, C must be abstract, and since C is the child of A and C is abstract, A must be
abstract. The other classes would need to be concrete so that we could instantiate objects in this hierarchy.
d. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work:
A[] collectionA = new A[20];
collectionA[3] = new D();
The first line makes an array of type A. It's possible to make an array of type A, even though A is abstract. (But
it's not possible to put an A object in this array, because we can't instantiate an abstract class.) The second line is
fine; it attempts to instantiate a concrete class, which is possible and desirable, and it attempts to put it an A
container, which is possible since D is a kind of A. So, this code works just fine.
e. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work:
C[] collectionC = new C[20];
collectionA[7] = new B();
The first line makes an array of type C. It's possible to make this array. The second line attempts to instantiate a
concrete class, B, which is possible. However, it fails in its attempt to put a B in a C container, which is impossible
because B is not a subclass of C.
3. CMPSC 221 / Spring 2011 / Exam 1 - Page 3 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
4. Consider the code below. Interpret it. Will it work? Why or why not? [3 pts.]
public class Z extends Y, X implements W, V
This attempts to make a class which is a subclass of two parent classes, which would be multiple inheritance. Java
doesn't support multiple inheritance, so this code won't work. Java does allow implementing multiple interfaces, which
the last clause correctly tries to do.
5. What are the three kinds of member functions of a class? [3 pts.]
constructor, modifier, accessor
6. Why don't we care about destructors in Java? [2 pts.]
Java has automatic garbage collection that takes care of this for us.
7. Give the command necessary to compile the file in which the class FloorLamp is implemented. [2 pts.]
javac FloorLamp.java
8. How are data members that tagged final in Java different from constants in C++? [2 pts.]
A C++ constant must be initialized at declaration, whereas a Java final data member can be initialized separately.
9. Consider the following list of classes: Car, SteeringWheel, Vehicle, Van, Minivan, AudioSystem,
ParkingLot. Your task is to describe all of the is-a and has-a relationships between these classes. Include an
inheritance hierarchy for all classes that fit. Present your response as clearly as possible and justify your choices (and any
interpretations you feel it necessary to clarify). [8 pts.]
See the inheritance hierarchy to the right. It shows the things that are
different types of the same concept. Cars, vans, and minivans are
specific types of vehicles and a minivan is a specific type of van. So,
• Car is-a Vehicle
• Van is-a Vehicle
• Minivan is-a Van
• Minivan is-a Vehicle
None of the other entities are kinds of vehicles, so they're not in the
hierarchy. Instead, it's believable any type of vehicle has a steering
wheel and audio system. Thus,
• Vehicle has-a SteeringWheel
and, in turn,
• Car has-a SteeringWheel
• Van has-a SteeringWheel
• Minivan has-a SteeringWheel
Likewise,
• Vehicle has-a AudioSystem
and, in turn,
• Car has-a AudioSystem
• Van has-a AudioSystem
• Minivan has-a AudioSystem.
Finally, a parking lot would be a container for vehicles, so
• ParkingLot has-a Vehicle
and, in turn,
• ParkingLot has-a Car
• ParkingLot has-a Van
• ParkingLot has-a Minivan
Vehicle
Car Van
Minivan
Alternatively, if we read each entry in this table as
[row heading] ______ [column heading],
then:
Vehicle Car Van Minivan Steering Audio Parking
Wheel System Lot
Vehicle --- --- --- --- has-a has-a ---
Car is-a --- --- --- has-a has-a ---
Van is-a --- --- --- has-a has-a ---
Minivan is-a --- is-a --- has-a has-a ---
SteeringWheel --- --- --- --- --- --- ---
AudioSystem --- --- --- --- --- --- ---
ParkingLot has-a has-a has-a has-a --- --- ---
4. CMPSC 221 / Spring 2011 / Exam 1 - Page 4 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
Part II: Programming Problems [60 points]
1. Suppose we have a fully-populated array of VideoGameEnemy objects (as in Lab 5 with a proper toString())
called enemies. We want to walk this array and print all details of all enemies to screen. [5 pts.]
a. Explain the logic you'd use to decide which kind of loop ideally solves this problem.
The first decision to consider in any "which loop to use" problem is whether the situation is determinate or not.
Here, we're walking an array and we know exactly how many iterations the loop would run before executing the
loop (5). Next, we note that we have no need for the indices of the array, so the enhanced for loop is best.
b. Now write that loop to solve this problem.
for(VideoGameEnemy vge : enemies)
{
System.out.println(vge);
}
2. Suppose have a class called CoordinateList2D and it has the following already defined: [23 pts.]
private double[] xPts; // x coordinates on Cartesian plane
private double[] yPts; // y coordinates on Cartesian plane, parallel to xPts
private int ct; // number of values in xPts and yPts
public void populateFromFile(String filename)
// PRE: filename denotes a file in the CLASSPATH directory formatted with two numeric
// quantities per line separated by whitespace
// POST: All lines of the file given by filename, and data is stored into xPts and yPts such
// that for line i, xPts[i] and yPts[i] are populated, overwriting any previous data.
// ct is set the number of points.
public void scaleUp(double factor)
// PRE: factor > 1
// POST: All values in xPts[0..(ct-1)] and yPts[0..(ct-1)] are factor times larger than they
// were prior to the call
a. Implement a default constructor for CoordinateList2D. [3 pts.]
// Best practice is to add a constant, e.g. MAX_SIZE, for the array's physical size
public CoordinateList2D()
{
xPts = new double[MAX_SIZE];
yPts = new double[MAX_SIZE];
ct = 0;
}
b. Working in CoordinateList2D, implement a method addPoint that takes as inputs an x and y coordinate and
adds them to the end of xPts and yPts. [5 pts.]
public void addPoint(double x, double y)
{
xPts[ct] = x;
yPts[ct] = y;
ct++;
}
Note: This question solves a similar problem to that of keeping track of a player's properties in Monopoly or reading in
several data points in Lab 1. (The difference is that we bring in parallel arrays.) In any event, the strategy is always
the same: initially allocate an array to a physical size that's large enough to hold as much or more data you
anticipate, initialize a logical size to 0, insert at the logical size, and increment the logical size at that point.
5. CMPSC 221 / Spring 2011 / Exam 1 - Page 5 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
c. Working in CoordinateList2D, implement either a toString() that lists all pairs of points as ordered pairs
with 2 decimal places and with line breaks between each point. For up to 5 points, instead implement display(),
which will just print these values to the console with the same formatting. [8 pts.]
public String toString()
{
String result = "";
for(int i = 0; i < ct; i++)
{
result += String.format("(%.2f, %.2f)n", xPts[i], yPts[i]);
}
return result;
}
d. Now, suppose you're writing a main in a client and you want to write a user program to get a filename for data and
a factor by which to enlarge the data, and then print the result to screen. Use a CoordinateList2D object to do
this. Prompt the user for inputs, displaying error messages for scale factors that don't make sense or would violate
any preconditions, and then display the scaled results. [7 pts.]
CoordinateList2D list;
String file;
double scale;
try
{
System.out.print("Enter filename: ");
file = input.next();
System.out.print("Enter positive scale factor: ");
scale = input.nextDouble();
list = new CoordinateList2D();
list.populateFromFile(file);
if(scale <= 1)
{
System.out.print("Scale factor must be larger than 1. Try again.");
}
else
{
list.scaleUp(scale);
System.out.print("Scaled Points: " + list);
}
}
catch(InputMismatchException ime)
{
System.out.println("Scale factor must be a number. Try again.");
}
This question was about using a CoordinateList2D object (3 points) and knowing when to use error handling
and exception handling (4 points). Credit was awarded here for the following key things, each a point:
• Calling the populateFromFile on an object (which requires that you've first constructed an object).
• Checking that the scale factor met the precondition of scaleUp.
• Giving an error message for the above, telling the user how to resolve the problem.
• Checking that the scale factor entered was numeric via exception handling.
• Giving an error message for the above, telling the user how to resolve the problem.
• Calling scaleUp on the object (which requires that you've first constructed an object).
• Display the scaled list using the object (which requires that you've first constructed an object).
All of the other details didn't necessarily affect your grade, except that credit was deducted for things that definitely
didn't work or for extremely poor practices like haphazardly declaring variables in the middle of logic.
6. CMPSC 221 / Spring 2011 / Exam 1 - Page 6 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
3. Mini Golf: Suppose you've been hired to help build the Objectville (virtual, of course) miniature golf course and you're
working on defining obstacles, e.g. stones, windmills, moving characters, sand traps, water traps, etc. [35 pts. total]
You'll start with a class called Obstacle, which has the following data dictionary:
protected String description; // phrase telling what the obstacle is and what it looks like
protected boolean isElectronic; // whether obstacle needs power to operate (true) or not (false)
protected int strokePenalty; // number of strokes a player whose ball stops on/in this
// obstacle suffers
You also have at your disposal the following constructor:
public Obstacle(String description, boolean isElectronic, int strokePenalty)
// PRE: description and isElectronic are initialized and strokePenalty >= 0
// POST: An Obstacle is constructed with data fields description, isElectronic, and
// strokePenalty set to the corresponding parameters
a. Create a default constructor for the Obstacle class. You decide what the default obstacle is. [5 pts.]
public Obstacle()
{
this("Large rock", false, 0);
}
b. One kind of an obstacle we'll have is called a Shuffler, which is a circular object that could be decorated in various
ways and designed to be placed on a course at a place where it might be advantageous for the ball's path to change.
They don't harm the player's score directly, but it's possible to have the Shuffler greatly help or hurt one's progress. If
a player's ball enters a Shuffler, it is spun around using a motor inside, and randomly projected outward some other
direction. (See illustration at the bottom of the next page.) Due to the physical limitations of building such a piece of
equipment, a Shuffler is only capable of directing a golf ball at angles of 0, 15, 30, 45, ..., 345 degrees clockwise
from where the golf ball entered and any of these angles is equally likely. Shufflers can be programmed such that
there is a minimum and maximum angle allowed. You'll implement this with a subclass of Obstacle called
Shuffler, which has the following additional data members:
private int minAngle; // smallest angle in degrees, with respect to entry point,
// ball could be directed
private int maxAngle; // largest angle in degrees, with respect to entry point,
// ball could be directed
First, write the first line of the class definition for Shuffler. [2 pts.]
public class Shuffler extends Obstacle
c. Given this information, write an initializer constructor that allows initialization of all configurable properties of a
Shuffler. [6 pts.]
public Shuffler(String details, int minAngle, int maxAngle)
{
super("Shuffler " + details, true, 0); // build description, these things need power,
// and don't directly harm scores
this.minAngle = minAngle; // set the new properties
this.maxAngle = maxAngle;
}
d. Write a precondition for the method from (c). [4 pts.]
// PRE: details is a description of this shuffler and could grammatically
// follow "Shuffler."
// 0 < minAngle < maxAngle and both minAngle and maxAngle are in degrees
// and are exact multiples of 15
This problem continues on the next page...
7. CMPSC 221 / Spring 2011 / Exam 1 - Page 7 of 7
Last 4 Digits of Student ID Number: ___ ___ ___ ___
e. Use the information from (b) to implement the following Shuffler member function: [9 pts.]
public int getNewAngle()
// POST: FCTVAL == the random angle a ball that enters this Shuffler will exit it, in degrees
{
int numAnglesPossible; // number of possible angles ball could be redirected
int outcomeNum; // random number of outcome between 0 and
// numAnglesPossible, inclusive
int resultAngle; // exit angle in degrees w.r.t. entry angle
numAnglesPossible = (maxAngle-minAngle)/15; // only allowed to use every 15th
// degree, so find how many
outcomeNum = (int)(Math.random()*(numAnglesPossible+1)); // allow for lowest case or most
// (needing +1 as random()
// never gives exactly 1)
resultAngle = minAngle + 15*outcomeNum; // scale back to multiples of 15
return resultAngle;
}
f. Suppose you're working in client code now. Create and initialize an array to hold three obstacles that are found on
Hole #9 (below): a water trap that causes a one-stroke penalty, a Shuffler that is painted bright orange and which can
redirect balls at angles of 15 to 210 degrees clockwise, and whatever you've decided the default obstacle is. [5 pts.]
Obstacle[] hole9Obstacles = new Obsacle[3];
hole9Obstacles[0] = new Obstacle("Water Trap", false, 1);
hole9Obstacles[1] = new Shuffler("colored bright orange", 15, 210);
hole9Obstacles[2] = new Obstacle();
g. Write a line of code to display a message you'd display to the console* to tell the user that his/her ball entered the
Shuffler from your array in (f) and the direction it's now headed after exiting. [4 pts.]
System.out.println("Your ball entered the Shuffler as has been redirected by "
+ ((Shuffler) hole9Obstacles[1]).getNewAngle() + " degrees.");
Just a rock (my default), but placed just
so it's in the way if you're in this corner
The Shuffler that could send you almost back to start, to
the water (oh no!), or angle you toward the goal
Water trap
* No, I wouldn't think you'd write a text-based golf game, although there's a certain nostalgic charm to the idea and I'm imagining a lot of interesting ASCII art.