Java final
504 flashcards · Other · by jkim6157
Consider the following code snippet: class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println(event); } } Timer t = new Timer(interval, listener); t.start(); What is wrong with this code?
The listener has not been attached to the Timerobject.
A ____ has an addActionListener() method for specifying which object is responsible for implementing the action associated with the object.
JButton
Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final variables.
inner
In UML, a dotted arrow with a triangular tip denotes ____________________.
interface implementation
Which of the following correctly defines a functional interface that, given an object, returns the value of a Coin?
(Object obj) -> ((Coin) obj).getValue()
Which of the following statements about an inner class is true? Which of the following statements about an inner class is true?
An inner class that is defined inside a method is not publicly accessible. The methods of an inner class can access variables declared in the enclosing scope.
Which of the following statements about a mock class is true?
A mock class provides a simplified implementation of the services of the actual class.
The method below is designed to return the smaller of two Comparable objects received as arguments. Assume that the objects are instances of the same class. Select the correct expression to complete the method. public static Comparable smaller(Comparable value1, Comparable value2) { if (_________________________ ) return value1; else return value2); }
value1.compareTo(value2) < 0
Consider the following code snippet: public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } } public class ButtonTester { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button); ActionListener listener = new ClickListener(); button.addActionListener(listener); ... } } Which of the following statements is correct?
A ClickListener object has been added as a listener for the action events that buttons generate.
Consider the following code snippet. public interface Measurable { double getMeasure(); } public class Coin implements Measurable { public Coin(double aValue, String aName) { ... } public double getMeasure() { return value; } ... } public class BankAccount implements Measurable { public BankAccount(double initBalance) { ... } public void getMeasure() { return balance; } ... } Which of the following statements is correct?
Coin dime = new Coin(0.1, "dime"); Measurable m = dime; "Measurable"
Consider the following code snippet: myImage.add(new Rectangle(10,10,10,10)); This code is an example of using ____.
an anonymous object.
Which of the following statements about interfaces is true?
You can define an interface variable that refers to an object only if the object belongs to a class that implements the interface.
Consider the following code snippet: public class MyMouseListener { public void mousePressed(MouseEvent event) { double x; double y; _______ System.out.println("x: " + x + ", y: " + y); } } Which of the following statements should be in the indicated position to print out where the mouse was pressed?
x = event.getX(); y = event.getY();
Consider the following declarations: public interface Encryptable { void encrypt(String key); } public class SecretText implements Encryptable { private String text; _____________________________ { // code to encrypt the text using encryption key goes here } } Which of the following method headers should be used to complete the SecretText class?
public void encrypt(String aKey)
Which of the following statements about interfaces is NOT true?
A class can implement only one interface type.
Which of the following correctly completes the Java statement shown to add a listener to a button using a lambda expression? button.addActionListener(_________________________________);
(ActionEvent event) -> System.out.println("Clicked!")
Using the given definition of the Measurableinterface: public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method: Measurable m = new BankAccount(); System.out.println(m.getBalance()); Which of the following statements is true?
The code does not compile because a variable of type Measurable does not have a getBalancemethod.
Consider the following class: public class Temperature implements Comparable { private int value; // other methods go here public int compareTo(Object otherObject) { Temperature otherTemp = (Temperature) otherObject; __________________________________; } } Which is the best statement to use to complete the compareTo() method?
return Integer.compare(value, otherTemp.value)
Consider the definition of the Measurableinterface and the code snippet defining the Inventory class: public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { . . . public double getMeasure() { return onHandCount; } } Why is it necessary to declare getMeasure as public in the Inventory class?
All methods in a class are not public by default.
Consider the following code snippet: import ____________________ import java.awt.event.ActionListener; /** An action listener that prints. */ public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } } Which of the following statements will complete this code?
java.awt.event.ActionEvent;
If the user presses and releases a mouse button in quick succession without moving the mouse, which methods of the MouseListener interface are called?
mousePressed, mouseReleased, andmouseClicked
To build a user interface that contains graphical components, the components ____.
must be added to a panel that is contained within a frame.
Assume that the Measurable interface is defined with a static sum method that computes the sum of the Measurable objects passed in as an array, and that BankAccount implements the Measurable interface. Also assume that there is a variable branchAccountsthat is an object reference to a populated array of BankAccount objects for a bank branch. Which of the following represents a correct invocation of the summethod to find the total balance of all accounts at the branch?
Measurable.sum(branchAccounts)
Consider the following class: public class Player implements Comparable { private String name; private int goalsScored; // other methods go here public int compareTo(Object otherObject) { __________________________________ return (goalsScored – otherPlayer.goalsScored); } } What statement can be used to complete the compareTo() method?
Player otherPlayer = (Player) otherObject;
If the user wants to paint a user-interface component in a special way whenever the mouse is pointing inside it, which methods of the MouseListener interface are useful?
mouseEntered and mouseExited
____ are generated when the user presses a key, clicks a button, or selects a menu item.
Events
Which of the following statements about the Object.clone method is NOT true?
Its return type is the same as the cloned object.
Consider the following class: public class Stock implements Comparable { private String name; private double price; // other methods go here public int compareTo(Object otherObject) { Stock otherStock = (Stock) otherObject; __________________________________; } } Which is the best statement to use to complete the compareTo() method?
return Double.compare(price, otherStock.price) "price, otherStock.price"
Consider the following code snippet that uses the parameterized Comparable interface. public class BowlingGame implements Comparable<BowlingGame> { private int score; ... public int compareTo(BowlingGame other) { _______________________________ } } Which of the following completes the compareToimplementation?
return score - other.score;
Assuming that the ClickListener class implements the ActionListener interface, what statement should be used to complete the following code segment? ClickListener listener = new ClickListener(); JButton myButton = new JButton("Submit"); JPanel myPanel = new JPanel(); myPanel.add(myButton); ______________________ //missing statement
myButton.addActionListener(listener);
Assume that the TimerListener class implements theActionListener interface. If the actionPerformedmethod in TimerListener needs to be executed once per second, what statement should be used to complete the following code segment? ActionListener listener = new TimerListener(); _________________________________ // missing statement timer.start();
Timer timer = new Timer(1000, listener);
When you use a timer, you need to define a class that implements the ____ interface.
ActionListener
Consider the definition of the Measurable interface and the code snippet defining the Inventory class: public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { . . . double getMeasure() { return onHandCount; } } What is wrong with this code?
The getMeasure() method must be declared as public. "public"
Listeners are typically implemented as inner classes. Which of the following statements is NOT true about inner class access to variables from the surrounding class?
Methods of an inner class cannot access variables from the surrounding class.
Which of the following statements is correct about inheritance and interfaces?
A class can extend at most one class and can implement multiple interfaces.
Suppose listener is an instance of a class that implements the MouseListener interface. How many methods does listener have?
at least 5
Consider the definition of the Measurable interface and the code snippet defining the Inventory class: public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { private int onHandCount; . . . double getMeasure() { return onHandCount; } } The compiler complains that the getMeasure method has a weaker access level than the Measurableinterface. Why?
All of the methods in a class have a default access level of package access, while the methods of an interface have a default access level of public.
Consider the following code snippet: public interface Measurable { double getMeasure(); ____________ boolean largerThan(Measurable other) { return getMeasure() > other.getMeasure(); } } Which of the following completes the interface declaration correctly?
default
An ____ belongs to a class whose methods describe the actions to be taken when a user clicks a user-interface graphical object.
event listener
If you have multiple classes in your program that have implemented the same interface in different ways, how is the correct method executed?
The Java virtual machine must locate the correct method by looking at the class of the actual object.
Consider the following declarations: public interface Measurer { int measure(Object anObject); } public class StringLengthMeasurer implements Measurer { public int measure(_________________) { String str = (String) anObject; return str.length(); } } What parameter declaration can be used to complete the callback measure method?
Object anObject
Consider the following class: public class BowlingGame implements Comparable { private int score; // other methods go here public int compareTo(Object otherObject) { BowlingGame otherGame = (BowlingGame) otherObject; __________________________________; } } What statement can be used to complete the compareTo() method?
return (score – otherGame.score)
How do you specify what the program should do when the user clicks a button?
Specify the actions to take in a class that implements the ActionListener interface.
Which of the following is an example of a functional interface, having a single abstract method?
ActionListener
What is the preferred way to implement event listeners?
Use inner classes as event listeners.
A/an ____ class defined in a method signals to the reader of your program that the class is not interesting beyond the scope of the method.
inner
Which of the following statements about a callback is NOT true?
A callback method declared in an interface must specify the class of objects that it will manipulate.
You wish to implement a callback method for an object created from a library class that you cannot change. What is the preferred way to accomplish this?
Use a helper class that implements the callback method.
Which of the following statements about lambda expressions is NOT true?
Lambda expressions cannot contain a method body enclosed in braces with a return statement.
Which of the following is true about a default method in an interface declaration?
A class that implements the interface can inherit the default behavior.
Using the given definition of the Measurableinterface: public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method: Measurable m = new BankAccount(); System.out.println(_________________________); Select the correct expression to display the balance of the bank account.
((BankAccount) m).getBalance()
Which statement about methods in an interface is true?
All methods in an interface are automatically public.
You wish to detect when the mouse is moved into a graphical component. Which methods of the MouseListener interface will provide this information?
mouseEntered
A class that implements an interface must provide an implementation for all ____ methods.
abstract
You have a class that extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data?
You must call the component object's repaint()method.
Using the following definitions of the Measurable and Named interfaces. public interface Measurable { double getMeasure(); } public interface Named { double getName(); } Assume BankAccount provides the code for the getMeasure() and getName() methods. Which of the following could correctly represent the class header for BankAccount?
public class BankAccount implements Measurable, Named
A method that has no implementation is called a/an ____ method.
abstract
Assume a class extends another class and implements an interface, both of which define the same method. Which statement is true about this conflict of inherited methods?
The subclass inherits the superclass method and ignores the default method from the interface.
Consider the following code snippet: public interface Sizable { int LARGE_CHANGE = 100; int SMALL_CHANGE = 20; void changeSize(); } Which of the following statements is true?
LARGE_CHANGE and SMALL_CHANGE are automatically public static final.
To use an interface, a class header should include which of the following?
The keyword implements and the name of the interface
Assuming that interface Resizable is declared elsewhere, consider the following class declaration: public class InnerClassExample { public static void main(String[] args) { class SizeModifier implements Resizable { // class methods } __________________________ // missing statement } } Which of the following declarations can be used to complete the main method?
Resizable something = new SizeModifier();
Assume a class implements two interfaces, both of which define a default method with the same signature. Which statement is true about this conflict of inherited methods?
The class must override the method and provide its own implementation.
Consider the following code snippet: public interface Measurable { double getMeasure(); ____________ double sum(Measurable[] objects) { // implementation to compute the sum of the Measurable objects } } Which of the following completes the interface declaration correctly?
static
Which of the following correctly defines a ButtonListener as an inner class and creates an instance of ButtonListener as a listener for the button?
class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Button clicked"); } } button.addActionListener(new ButtonListener()); Memorize: "ActionEvent event button.addActionListener(new ButtonListener());"
The methods of an ____ describe the actions to be taken when an event occurs.
event listener
Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code?
The class has implemented the wrong interface.
What does the MouseAdapter class provide?
The MouseAdapter class implements all of the methods of the MouseListener interface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of theMouseListener interface.
Consider the following code snippet: BankAccount account = new BankAccount(500); Which of the following statements correctly clones the account?
BankAccount clonedAccount = (BankAccount) account.clone();
END OF CHAPTER 10
START OF CHAPTER 9
Which keyword is used to create a subclass?
extends
Consider the following code snippet: Employee programmer = new Employee(10254, "exempt"); String s = programmer.toString(); Assume that the Employee class has not implemented its own toString() method. What value will scontain when this code is executed?
s will contain the class name of the programmerobject followed by a hash code. "hash code"
What reserved word in a method definition ensures that subclasses cannot override the method?
final
Suppose the abstract class Message is defined below public abstract class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } public abstract String translate(); } A concrete subclass of Message, called FrenchMessage, is defined. Which methods must FrenchMessage define?
translate() only
All hamsters are rodents and all rodents are mammals. What hierarchy best captures this information?
Mammal is a superclass of Rodent and Rodent is a superclass of Hamster
Consider the classes shown below: public class Parent { public void doSomething() // method 1 { /* Implementation not shown */ } } public class Child extends Parent { public void doSomething(int n) // method 2 { /* Implementation not shown */ } public void doSomething() // method 3 { /* Implementation not shown */ } } If the variable kid is defined below, which version of the doSomething method can be called on the variable kid? Child kid = new Child();
Methods 2 and 3 only "child kid"
Consider the following code snippet: public class Auto extends Vehicle { . . . public Auto(int numberAxles) { super(numberAxles); } } What does this code do?
It invokes the constructor of the Vehicle class from within the constructor of the Auto class. "constructor, vehicle, Auto"
If a subclass defines the same method name and the same parameter types for a method that appears in its superclass, which statement is true?
the subclass method overrides the superclass method.
Which class represents a more specific entity in an inheritance hierarchy?
Subclass
You are creating a class inheritance hierarchy about motor vehicles that will contain classes named Vehicle, Auto, and Motorcycle. Which of the following statements is correct?
Vehicle should be the superclass, while Autoand Motorcycle should be the subclasses. "superclass"
In Java, two methods can have the same name provided that what is true?
They must differ in their parameter types.
Consider the following code snippet: public void deposit(double amount) { transactionCount++; super.deposit(amount); } Which of the following statements is true?
This method calls a public method in its superclass.
Consider the classes shown below: public class Parent { public void doSomething(){/* Implementation not shown */} } public class Child extends Parent { public void doAnotherThing(){/* Implementation not shown */} } Which lines in the following code will compile without error? Parent kid = new Child(); kid.doSomething(); // line 1 kid.doAnotherThing(); // line 2
Line 1 only
What is a class called that represents the most general entity in an inheritance hierarchy?
Superclass.
Consider the following inheritance hierarchy diagram: Which of the following statements is correct?
Auto is a subclass of LandVehicle, and LandVehicle is a subclass of Vehicle.
Consider the following code snippet: public class Vehicle { private String manufacturer; . . . public void setVehicleClass(double numberAxles) { . . . } } If a Motorcycle class is created as a subclass of theVehicle class, which of the following statements is correct?
A Motorcycle object inherits and can directly use the method setVehicleClass but cannot directly use the instance variable manufacturer. "Motorcycle, setVehicleClass, manufacturer"
Consider the following code snippet: Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from theVehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct?
The toString() method of the Object class will be used when this code is executed. "toString(), object"
Consider the following code snippet: Vehicle aVehicle = new Auto(); aVehicle.moveForward(200); If the Auto class inherits from the Vehicle class, and both classes have an implementation of themoveForward method with the same set of parameters and the same return type, which statement is correct?
The moveForward method of the Auto class will be executed. "moveForward, Auto"
Which of the following statements about classes is true?
You can create an object from a concrete class, but not from an abstract class.
Consider the classes shown below: public class Parent { private int value = 100; public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } } What is the output of the following lines of code? Child kid = new Child(-14); Parent adult = new Parent(); System.out.println(kid.getValue() + " " + adult.getValue());
100 100
Suppose the class Value is partially defined below public class Value { private int number; public int getValue() { return number; } } A subclass of Value, LargerValue, is defined with a getValue method that returns twice the value of the parent. Which line is the body of LargerValue'sgetValue method?
return super.getValue() * 2;
Consider the following code snippet: public class Motorcycle extends Vehicle { . . . public Motorcycle(int numberAxles) { super.numberAxles = numberAxles; } } What does this code do?
It attempts to access directly an instance variable of the Vehicle superclass rather than using a constructor or an accessor.
Consider the following code snippet, which is meant to override the equals() method of the Object class: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code?
A class cannot change the parameters of a superclass method when overriding it.
Consider the following code snippet: Employee anEmployee = new Programmer(); String emp = anEmployee.toString(); Assume that the Programmer class inherits from theEmployee class, and only the Employee class has an implementation of the toString() method. Which of the following statements is correct?
The toString() method of the Employee class will be used when this code is executed. "Employee"
Consider the following class hierarchy: public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String getType() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { . . . } } public class Auto extends LandVehicle { public Auto(String type) { . . . } } Which of the following code fragments is NOT valid in Java?
LandVehicle myAuto = new Vehicle("sedan"); "LandVehicle, Vehicle"
Consider the following code snippet: double salary = 45000.00; String sal = "Current salary is " + salary; Which of the following statements is correct?
No toString() method is being used to set the value of salary.
Which of the following is true regarding subclasses?
A subclass has no access to private instance variables of its superclass.
When declared as protected, which statement is true about the access to data in an object?
The data is accessible only by that class's methods, by all of its subclasses, and by methods in classes within the same package.
Which of the following statements about inheritance is correct?
You can always use a subclass object in place of a superclass object.
Consider the Counter class below. public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variables declared below, what is the value of num1.equals(num2)? Counter num1 = new Counter(); Counter num2 = num1;
true "Counter num2 = num1;
With a few exceptions, what access should instance variables of classes always have?
private