Unit 5 Topic Questions - Writing Classes
Unit 5 Topic Questions - Writing Classes
1. The Car class will contain two string attributes for a car’s make and model. The class will also contain a
constructor.
Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?
public String make;
public String model;
(A) public Car(String myMake, String myModel)
{ /* implementation not shown */ }
public String make;
public String model;
(B) private Car(String myMake, String myModel)
{ /* implementation not shown */ }
private String make;
private String model;
(C) public Car(String myMake, String myModel)
{ /* implementation not shown */ }
public String make;
private String model;
(D) private Car(String myMake, String myModel)
( /* implementation not shown */ }
private String make;
private String model;
(E) private Car(String myMake, String myModel)
{ /* implementation not shown */ }
2. The Date class below will contain three int attributes for day, month, and year, a constructor, and a
setDate method. The setDate method is intended to be accessed outside the class.
Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?
3. The Player class below will contain two int attributes and a constructor. The class will also contain a
method getScore that can be accessed from outside the class.
Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?
4. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.
Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined
in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will
not receive full credit.
This question involves the implementation of the AddtionPattern class, which generates a number pattern.
The AdditionPattern object is constructed with two positive integer parameters, as described below.
The first positive integer parameter indicates the starting number in the pattern.
The second positive integer parameter indicates the value that is to be added to obtain each subsequent number in
the pattern.
The following table illustrates the behavior of an AdditionPattern object that is instantiated by the following
statement.
Value Returned
Method Call (blank if no Explanation
value)
The current number is initially the starting
plus3.currentNumber(); 2
number in the pattern.
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (5).
plus3.currentNumber(); 5 The current number is 5.
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (8).
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (11).
plus3.currentNumber(); 11 The current number is 11.
Move to the previous number in the pattern
plus3.prev();
(8).
Move to the previous number in the pattern
plus3.prev();
(5).
Move to the previous number in the pattern
plus3.prev();
(2).
plus3.currentNumber(); 2 The current number is 2.
There is no previous number in the pattern
plus3.prev();
prior to 2, so no action is taken.
plus3.currentNumber(); 2 The current number is 2.
Write the complete AdditonPattern class. Your implementation must meet all specifications and conform to
all examples.
Which of the following best describes the behavior of the code segment?
(A) Exactly 5 Element objects are created.
(B) Exactly 10 Element objects are created.
Between 0 and 5 Element objects are created, and Element.max_value is increased only for the
(C)
first object created.
Between 1 and 5 Element objects are created, and Element.max_value is increased for every
(D)
object created.
Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one
(E)
object created.
Which of the following is a true statement about the behavior of WordClass objects?
(A) A WordClass object can change the value of the variable word more than once.
(B) Every time a WordClass object is created, the max_word variable is referenced.
(C) Every time a WordClass object is created, the value of the max_word variable changes.
(D) No two WordClass objects can have their word length equal to the length of max_word.
(E) The value of the max_word variable cannot be changed once it has been initialized.
The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the
number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times
the per mile rate.
Which of the following code segments should replace /* missing code */ so that the calculateFee
method will work as intended?
8. Consider the definition of the Person class below. The class uses the instance variable adult to indicate
whether a person is an adult or not.
{
private String name;
private int age;
private boolean adult;
public Person (String n, int a)
{
name = n;
age = a;
if (age >= 18)
{
adult = true;
}
else
{
adult = false;
}
}
}
Which of the following statements will create a Person object that represents an adult person?
(A) Person p = new Person ("Homer", "adult");
(B) Person p = new Person ("Homer", 23);
(C) Person p = new Person ("Homer", "23");
(D) Person p = new Person ("Homer", true);
(E) Person p = new Person ("Homer", 17);
9. Consider the following class definition. Each object of the class Item will store the item’s name as itemName,
the item’s regular price, in dollars, as regPrice, and the discount that is applied to the regular price when the
item is on sale as discountPercent. For example, a discount of 15% is stored in discountPercent as
0.15.
Which of the following code segments, found in a class other than Item, can be used to create an item with a
regular price of $10 and a discount of 25% ?
10. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.
Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined
in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will
not receive full credit.
The following class represents a customer. The variable name represents the name of the customer, and the variable
currAccNum represents the customer’s account number. Each time a Customer object is created, the static variable
nextAccNum is used to assign the customer’s account number.
public Customer(String n)
{
name = n;
currAccNum = nextAccNum;
nextAccNum++;
}
}
(a) Write a method for the Customer class that that will return a string representing a bill notice when passed a
double value representing an amount due.
For example, if the customer has name "Jeremiah", has account number 3, and has amount due 50.50, the method
should return a string in the following format.
Write the method below. Your implementation must conform to the example above.
(b) Write a method for the Customer class that returns the value of the next account number that will be assigned.
(c) A student has written the following method to be included in the Customer class. The method is intended to
update the name of a customer but does not work as intended.
{
name = name;
}
Write a correct implementation of the updateName method that avoids the error in the student’s implementation.
11. Consider the following class, which uses the instance variable balance to represent a bank account balance.
The deposit method is intended to increase the account balance by the deposit amount and then return the
updated balance. Which of the following code segments should replace /* missing code */ so that the
deposit method will work as intended?
amount = balance + amount;
(A) return amount;
balance = amount;
(B) return amount;
balance = amount;
(C) return balance;
balance = balance + amount;
(D) return amount;
Consider the following code segment, which appears in a method in a class other than Password. The code
segment does not compile.
Which of the following best identifies the reason the code segment does not compile?
(A) The code segment attempts to access the private variable password from outside the Password class.
(B) The new password cannot be the same as the old password.
(C) The Password class constructor is invoked incorrectly.
(D) The reset method cannot be called from outside the Password class.
(E) The reset method does not return a value that can be printed.
Which of the following best explains why the computeArea method will cause a compilation error?
(A) Local variables declared inside a method cannot be declared as public or private.
(B) Local variables declared inside a method must all be private.
(C) Local variables declared inside a method must all be public.
(D) Local variables used inside a method must be declared at the end of the method.
(E) Local variables used inside a method must be declared before the method header.
Which of the following best explains why the class will not compile?
(A) The class is missing an accessor method.
(B) The instance variables name and number should be designated public instead of private.
(C) The return type for the Info constructor is missing.
(D) The variable name is not defined in the changeName method.
(E) The variable num is not defined in the addNum method.
Which of the following best identifies the reason the class does not compile?
(A) The constructor header is missing a return type.
(B) The updateItems method is missing a return type.
(C) The constructor should not have a parameter.
(D) The updateItems method should not have a parameter.
(E) The instance variable numItems should be public instead of private.
16. Consider the following Bugs class, which is intended to simulate variations in a population of bugs. The
population is stored in the method’s int attribute. The getPopulation method is intended to allow methods
in other classes to access a Bugs object’s population value; however, it does not work as intended.
public Bugs(int p)
{
population = p;
}
Which of the following best explains why the getPopulation method does NOT work as intended?
Which of the following best explains the reason why the class will not compile?
(A) The variable numGallons is not declared in the getNumGallons method.
(B) The variable saltWater is not declared in the isSaltWater method.
(C) The isSaltWater method does not return the value of an instance variable.
(D) The value returned by the getNumGallons method is not compatible with the return type of the method.
(E) The value returned by the isSaltWater method is not compatible with the return type of the method.
18. Consider the following class definition. The class does not compile.
The accessor method getScore is intended to return the score of a Player object. Which of the following
best explains why the class does not compile?
(A) The getScore method should be declared as private.
(B) The getScore method requires a parameter.
(C) The return type of the getScore method needs to be defined as double.
(D) The return type of the getScore method needs to be defined as String.
(E) The return type of the getScore method needs to be defined as void.
19. Consider the following while loop. Assume that the int variable k has been properly declared and
initialized.
while (k < 0)
{
System.out.print("*");
k++;
}
Which of the following ranges of initial values for k will guarantee that at least one "*" character is printed?
I. k < 0
II. k = 0
III. k > 0
(A) I only
(B) III only
(C) I and II only
(D) II and III only
(E) I, II, and III
Consider the following code segment, which appears in a class other than Item or ItemCollection.
21. The following method is intended to return a string containing the character at position n in the string str. For
example, getChar("ABCDE", 2) should return "C".
/* missing precondition */
public String getChar(String str, int n)
{
return str.substring(n, n + 1);
}
Which of the following is the most appropriate precondition for the method so that it does not throw an exception?
(A) /* Precondition: 0 < n < str.length() - 1 */
(B) /* Precondition: 0 <= n <= str.length() - 1 */
(C) /* Precondition: 0 <= n <= str.length() */
(D) /* Precondition: n > str.length() */
(E) /* Precondition: n >= str.length() */
22. Consider the following method, which is intended to return the product of 3 and the nonnegative difference
between its two int parameters.
Which, if any, precondition is required so that the method works as intended for all values of the parameters that
satisfy the precondition?
(A) num1 > 0, num2 > 0
(B) num1 >= 0, num2 >= 0
(C) num1 >= num2
(D) num2 >= num1
(E) No precondition is required.
23. In the Toy class below, the raisePrice method is intended to increase the value of the instance variable
price by the value of the parameter surcharge. The method does not work as intended.
Which of the following changes should be made so that the class definition compiles without error and the method
raisePrice works as intended?
(A) Replace line 14 with surcharge += price;.
(B) Replace line 14 with price += surcharge;.
(C) Replace line 14 with return price += surcharge;.
(D) Replace line 12 with public raisePrice (double surcharge).
(E) Replace line 12 with public double raisePrice (double surcharge).
The following code segment appears in a method in a class other than Something.
Which of the following best describes the behavior of the code segment?
The code segment does not compile because the increment method should be called on an object of the
(A)
class Something, not on the class itself.
The code segment creates a Something object s. The class Something’s static variable count is
(B)
initially 0, then increased by 1.
The code segment creates a Something object s. The class Something’s static variable count is
(C)
initially 0, then increased by 5, then increased by 1.
The code segment creates a Something object s. After executing the code segment, the object s has a
(D)
count value of 1.
The code segment creates a Something object s. After executing the code segment, the object s has a
(E)
count value of 5.
The following statement appears in a method in a class other than Tester. It is intended to create a new
Tester object t with its attributes set to 10 and 20.
Which of the following can be used to replace /* missing constructor */ so that the object t is correctly
created?
The following code segment appears in a class other than MenuItem or Combo.
The following code segment appears in a method in a class other than Class1 or Class2.
(A) 2
(B) 1
(C) 0
(D) -2
(E) Nothing is printed because the code segment does not compile.
The class contains the withdraw method, which is intended to update the instance variable balance under
certain conditions and return a value indicating whether the withdrawal was successful. If subtracting
withdrawAmount from balance would lead to a negative balance, balance is unchanged and the
withdrawal is considered unsuccessful. Otherwise, balance is decreased by withdrawAmount and the
withdrawal is considered successful.
Which of the following code segments can replace /* missing code */ to ensure that the withdraw method
works as intended?
I.
if (withdrawAmount > balance)
{
return "Overdraft";
}
else
{
balance -= withdrawAmount;
return true;
}
II.
if (withdrawAmount > balance)
{
return false;
}
else
{
balance -= withdrawAmount;
return balance;
}
III.
if (withdrawAmount > balance)
{
return false;
}
else
{
balance -= withdrawAmount;
return true;
}
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III
29. The class Worker is defined below. The class includes the method getEarnings, which is intended to return
the total amount earned by the worker.
The following code segment appears in a method in a class other than Worker. The code segment is intended to
print the value 800.0, but instead prints a different value because of an error in the Worker class.