Java 2 ch 8, 9

¡Supera tus tareas y exámenes ahora con Quizwiz!

If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect?

It is a side effect; this kind of side effect is common in object-oriented programming.

What is the significance of the EPSILON argument in the assertEquals method?

It is a tolerance threshold for comparing floating-point numbers. We want the equality test to pass if there is a small roundoff error.

Is the substring method of the String class an accessor or a mutator?

It is an accessor—calling substring doesn't modify the string on which the method is invoked. In fact, all methods of the String class are accessors

Look at the direction instance variable in the bug example in Section 8.3.6. This is an example of which pattern?

It is an example of the "state pattern" described in Section 8.3.5. The direction is a state that changes when the bug turns, and it affects how the bug moves.

Is the method call Math.sqrt(2) resolved through dynamic method lookup?

No. This is a static method of the Math class. There is no implicit parameter object that could be used to dynamically look up a method.

Which of the following are packages? a. java b. java.lang c. java.util d. java.lang.Math

(a) No; (b) Yes; (c) Yes; (d) No

Suppose q is an object of the class Question and cq an object of the class ChoiceQuestion. Which of the following calls are legal? a. q.setAnswer(response) b. cq.setAnswer(response) c. q.addChoice(choice, true) d. cq.addChoice(choice, true)

. a, b, d

In the Manager class, provide the method header (but not the implementation) for a method that overrides the getSalary method from the class Employee.

. public class Manager extends Employee { . . . public double getSalary() { . . . } }

In the Manager class of Self Check 9, override the getSalary method so that it returns the sum of the salary and the bonus.

. public double getSalary() { return super.getSalary() + bonus; }

Suppose your homework assignments are located in the directory /home/me/ cs101 (c:\Users\Me\cs101 on Windows). Your instructor tells you to place your homework into packages. In which directory do you place the class hw1.problem1. TicTacToe Tester?

/home/me/cs101/hw1/problem1 or, on Windows, c:\Users\Me\cs101\hw1\problem1.

Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?

Because every manager is an employee but not the other way around, the Manager class is more specialized. It is the subclass, and Employee is the superclass

Why does the call System.out.println(System.out); produce a result such as java.io.PrintStream@7a84e4?

Because the implementor of the PrintStream class did not supply a toString method.

Look again at the implementation of the addChoice method that calls the setAnswer method of the superclass. Why don't you need to call super.setAnswer?

Because there is no ambiguity. The subclass doesn't have a setAnswer method.

What are the inheritance relationships between classes BankAccount, CheckingAccount, and SavingsAccount?

CheckingAccount and SavingsAccount both inherit from the more general class BankAccount

Consider the task of finding numbers in a string. For example, the string "In 1987, a typical personal computer cost $3,000 and had 512 kilobytes of RAM." has three numbers. Break this task down into a sequence of simpler tasks.

Here is one plan: a. Find the position of the first digit in a string. b. Find the position of the first non-digit after a given position in a string. c. Extract the first integer from a string (using the preceding two steps). d. Print all integers from a string. (Use the first three steps, then repeat with the substring that starts after the extracted integer.)

Provide a JUnit test class with one test case for the Earthquake class in Chapter 5.

Here is one possible answer. public class EarthquakeTest { @Test public void testLevel4() { Earthquake quake = new Earthquak(4); Assert.assertEquals( "Felt by many people, no destruction", quake.getDescription()); } }

Why should coupling be minimized between classes?

If a class doesn't depend on another, it is not affected by interface changes in the other class.

Why is it a good idea to minimize dependencies between classes?

If a class doesn't depend on another, it is not affected by interface changes in the other class.

If account is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which account refers?

It belongs to the class BankAccount or one of its subclasses.

Suppose we want to count the number of transactions in a bank account in a statement period, and we add a counter to the BankAccount class: public class BankAccount { private int transactionCount; . . . } In which methods does this counter need to be updated?

It needs to be incremented in the deposit and withdraw methods. There also needs to be some method to reset it after the end of a statement period.

Should a class Quiz inherit from the class Question? Why or why not?

It shouldn't. A quiz isn't a question; it has questions.

What is a simple rule of thumb for finding classes?

Look for nouns in the problem description.

What is the rule of thumb for finding classes?

Look for nouns in the problem description.

In an e-mail system, messages are stored in a mailbox. Draw a UML diagram that shows the appropriate aggregation relationship.

Mailbox<--Message

Name a static constant of the Math class.

Math.PI

Why does the Coin class not depend on the CashRegister class?

None of the coin operations require the CashRegister class.

Is the Rectangle class immutable?

No—translate is a mutator method.

Is a Java program without import statements limited to using the default and java.lang packages?

No—you can use fully qualified names for all other classes, such as java.util.Random and java.awt.Rectangle.

Suppose you are asked to find all words in which no letter is repeated from a list of words. What simpler problem could you try first?

Of course, there is more than one way to simplify the problem. One way is to print the words in which the first letter is not repeated.

Suppose the invoice is to be saved to a file. Name a likely collaborator

PrintStream.

Declare an array quiz that can hold a mixture of Question and ChoiceQuestion objects

Question[] quiz = new Question[SIZE];

What do you do if a CRC card has ten responsibilities?

Reword the responsibilities so that they are at a higher level, or come up with more classes to handle the responsibilities.

Suppose the setName method in Section 8.3.4 is changed so that it returns true if the new name is set, false if not. Is this a good idea?

Section 8.2.3 suggests that a setter should return void, or perhaps a convenience value that the user can also determine in some other way. In this situation, the caller could check whether newName is blank, so the change is fine.

Why is the CashRegister class from Chapter 4 not cohesive?

Some of its features deal with payments, others with coin values.

Name two static variables of the System class.

System.in and System.out.

In the example in Section 8.3.3, why is the add method required? That is, why can't the user of a Question object just call the add method of the ArrayList<String> class?

The ArrayList<String> instance variable is private, and the class users cannot acccess it.

Consider the CashRegisterTester class of Section 8.2. On which classes does it depend?

The CashRegisterTester class depends on the CashRegister, Coin,and System classes.

Consider the Question and ChoiceQuestion objects of Chapter 9. How are they related?

The ChoiceQuestion class inherits from the Question class.

Which class is responsible for computing the amount due? What are its collaborators for this task?

The Invoice class is responsible for computing the amount due. It collaborates with the LineItem class.

Consider the Quiz class described in Section 12.2.2. Suppose a quiz contains a mixture of Question and ChoiceQuestion objects. Which classes does the Quiz class depend on?

The Quiz class depends on the Question class but probably not ChoiceQuestion, if we assume that the methods of the Quiz class manipulate generic Question objects, as they did in Chapter 9.

What are all the superclasses of the JFrame class? Consult the Java API documentation or Appendix D.

The classes Frame, Window, and Component in the java.awt package, and the class Object in the java.lang package.

Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Who was the inventor of Java?"; Question q = (Question) obj; q.display();

The code will compile, but the second line will throw a class cast exception because Question is not a superclass of String.

In How To 3.1, the CashRegister class does not have a getTotalPurchase method. Instead, you have to call receivePayment and then giveChange. Which recommendation of Section 8.2.4 does this design violate? What is a better alternative?

The giveChange method is a mutator that returns a value that cannot be determined any other way. Here is a better design. The receivePayment method could decrease the purchase instance variable. Then the program user would call receivePayment, determine the change by calling getAmountDue, and call the clear method to reset the cash register for the next sale.

What is wrong with the following implementation of the display method? public class ChoiceQuestion { . . . public void display() { System.out.println(text); for (int i = 0; i < choices.size(); i++) { int choiceNumber = i + 1; System.out.println(choiceNumber + ": " + choices.get(i)); } } }

The method is not allowed to access the instance variable text from the superclass.

The following method computes the average of an array of numbers: public static double average(double[] values) Why should it not be defined as an instance method?

The method needs no data of any object. The only required input is the values argument.

Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Hello"; System.out.println(obj.length());

The second line will not compile. The class Object does not have a method length.

Consider an Employee class with properties for tax ID number and salary. Which of these properties should have only a getter method, and which should have getter and setter methods?

The tax ID of an employee does not change, and no setter method should be supplied. The salary of an employee can change, and both getter and setter methods should be supplied.

What is wrong with the following implementation of the display method? public class ChoiceQuestion { . . . public void display() { this.display(); for (int i = 0; i < choices.size(); i++) { int choiceNumber = i + 1; System.out.println(choiceNumber + ": " + choices.get(i)); } } }

The type of the this reference is ChoiceQuestion. Therefore, the display method of ChoiceQuestion is selected, and the method calls itself.

Assuming that x is an object reference, what is the value of x instanceof Object?

The value is false if x is null and true otherwise.

Why don't we simply store all objects in variables of type Object?

There are only a few methods that can be invoked on variables of type Object.

In a library management system, what would be the relationship between classes Patron and Author?

There would be no relationship.

Why do the format methods return String objects instead of directly printing to System.out?

This design decision reduces coupling. It enables us to reuse the classes when we want to show the invoice in a dialog box or on a web page

Looking at the invoice in Figure 1, what is a likely responsibility of the Customer class?

To produce the shipping address of the customer.

You are implementing a system to manage a library, keeping track of which books are checked out by whom. Should the Book class aggregate Patron or the other way around?

Typically, a library system wants to track which books a patron has checked out, so it makes more sense to have Patron aggregate Book. However, there is not always one true answer in design. If you feel strongly that it is important to identify the patron who checked out a particular book (perhaps to notify the patron to return it because it was requested by someone else), then you can argue that the aggregation should go the other way around.

Consider the method doSomething(Car c). List all vehicle classes from Figure 1 whose objects cannot be passed to this method

Vehicle, truck, motorcycle

Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How about MovePiece?

Yes (ChessBoard) and no (MovePiece).

Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and variables static. Then main can call the other static methods, and all of them can access the static variables. Will Harry's plan work? Is it a good idea?

Yes, it works. Static methods can access static variables of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs

If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect?Consider the Student class of Chapter 7. Suppose we add a method void read(Scanner in) { while (in.hasNextDouble()) { addScore(in.nextDouble()); } } Does this method have a side effect other than mutating the scores?

Yes—the method affects the state of the Scanner argument.

You want to remove "red eyes" from images and are looking for red circles. What simpler problem can you start with?

You can look for a single red pixel, or a block of nine neighboring red pixels

Consider the code fragment ChoiceQuestion cq = . . .; // A non-null value cq.display(); Which actual method is being called?

You cannot tell from the fragment—cq may be initialized with an object of a subclass of ChoiceQuestion. The display method of whatever object cq references is invoked.

You need to write a program for DNA analysis that checks whether a substring of one string is contained in another string. What simpler problem can you solve first?

You could first write a program that prints all substrings of a given string.

Suppose we want to enhance the CashRegister class in How To 3.1 to track the prices of all purchased items for printing a receipt. Which instance variable should you provide? Which methods should you modify?

You need to supply an instance variable that can hold the prices for all purchased items. This could be an ArrayList<Double> or ArrayList<String>, or it could simply be a String to which you append lines. The instance variable needs to be updated in the recordPurchase method. You also need a method that returns the receipt.

Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? a. BankAccount account = new SavingsAccount(); b. SavingsAccount account2 = new BankAccount(); c. BankAccount account = null; d. SavingsAccount account2 = account;

a only

Which methods does the Manager class from Self Check 9 inherit?

getName, setName, setBaseSalary

Which instance variables does the Manager class from Self Check 7 have?

name, baseSalary, and bonus

In the Manager class of Self Check 7, override the getName method so that managers have a * before their name (such as *Lin, Sally).

public String getName() { return "*" + super.getName(); }

Suppose the class Employee is declared as follows: public class Employee { private String name; private double baseSalary; public void setName(String newName) { . . . } public void setBaseSalary(double newSalary) {...} public String getName() { . . . } public double getSalary() { . . . } } Declare a class Manager that inherits from the class Employee and adds an instance variable bonus for storing a salary bonus. Omit constructors and methods.

public class Manager extends Employee { private double bonus; // Constructors and methods omitted }


Conjuntos de estudio relacionados

Restaurant Tyler Menu Test 08/21

View Set

3.4.3 Pre-Cal Graphing Polynomial Functions

View Set

BIO60 Lab Exam 1: Intro to Scientific Method

View Set

physics and human affairs final uark

View Set

PSYCHOLOGY CHAPTER 12: Social Psychology

View Set