AP CS Unit 5

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

The Employee class will contain a String attribute for an employee's name and a double attribute for the employee's salary. Write a correct Implementation of the class

public class Employee { private String name; private double salary; // constructor and methods not shown }

public class Class1 { private int val1; public Class1() { val1 = 1; } public void init() { Class2 c2 = new Class2(); c2.init(this, val1); } public void update(int x) { val1 -= x; } public int getVal() { return val1; } } public class Class2 { private int val2; public Class2() { val2 = 2; } public void init(Class1 c, int y) { c.update(val2 + y); } } The following code segment appears in a method in a class other than Class1 or Class2. Class1 c = new Class1(); c.init(); System.out.println(c.getVal()); What, if anything, is printed as a result of executing the code segment?

-2

Consider the following method. /* missing precondition */ public void someMethod(int j, int k, String oldString) { String newString = oldString.substring(j, k); System.out.println("New string: " + newString); } Which of the following is the most appropriate precondition for someMethod so that the call to substring does not throw an exception? /* Precondition: 0 <= oldString.length() */ /* Precondition: 0 < j and 0 < k */ /* Precondition: 0 <= j and 0 <= k */ /* Precondition: j <= k */ /* Precondition: 0 <= j <= k <= oldString.length() */

/* Precondition: 0 <= j <= k <= oldString.length() */

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? /* Precondition: 0 < n < str.length()- 1 */ /* Precondition: 0 <= n <= str.length()- 1 */ /* Precondition: 0 <= n <= str.length() */ /*Precondition: n > str.length() */ /* Precondition: n >= str.length() */

/* Precondition: 0 <= n <= str.length()- 1 */

The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5. /* missing precondition */ public static int addItUp(int m, int n) { int sum = 0; for (int j = m; j <= n; j++) { sum += j; } return sum; } Which of the following is the most appropriate precondition for the method? /* Precondition: m <= n */ /* Precondition: n <= m */ /* Precondition: m >= 0 and n >= 0 */ /* Precondition: m <= 0 and n <= 0 */ /* Precondition: m <= 0 and n >= 0 */

/* Precondition: m <= n */

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided? 0 <= index < phrase.length() 0 <= index < key.length() 0 <= index < phrase.length() + key.length() 0 <= index < phrase.length() - key.length() 0 <= index < phrase.length() - index

0 <= index < phrase.length() - key.length()

public class Student { private String name; private double gpa; public Student(String n, double g) { name = n; gpa = g; } public String compareGPA(Student other) { if (this.gpa < other.gpa) { return other.name; } else if (gpa > other.gpa) { return name; } else return "Same"; } } The following code segment appears in a method in a class other than Person. Student a = new Student ("Alice", 3.7); Student b = new Student ("Bob", 3.5); System.out.println(a.compareGPA(b)); What, if anything, is printed as a result of executing the code segment?

Alice

Consider the following class definition. public class Contact { private String contactName; private String contactNumber; public Contact(String name, String number) { contactName = name; contactNumber = number; } public void doSomething() { System.out.println(this); } public String toString() { return contactName + " " + contactNumber; } } The following code segment appears in another class. Contact c = new Contact("Alice", "555-1234"); c.doSomething(); c = new Contact("Daryl", ""); c.doSomething(); What is printed as a result of executing the code segment?

Alice 555-1234 Daryl

Consider the following class definition. public class Person { private String name; private int feet; private int inches; public Person(String nm, int ft, int in) { name = nm; feet = ft; inches = in; } public int heightInInches() { return feet * 12 + inches; } public String getName() { return name; } public String compareHeights(Person other) { if (this.heightInInches() < other.heightInInches()) { return name; } else if (this.heightInInches() > other.heightInInches()) { return other.getName(); } else return "Same"; } } The following code segment appears in a method in a class other than Person. Person andy = new Person("Andrew", 5, 6); Person ben = new Person("Benjamin", 6, 5); System.out.println(andy.compareHeights(ben)); What, if anything, is printed as a result of executing the code segment? Andrew Benjamin Same Nothing is printed because the method heightInInches cannot be called on this. Nothing is printed because the compareHeights method in the Person class cannot take a Person object as a parameter.

Andrew

Consider the following class definition. public class BoolTest { private int one; public BoolTest(int newOne) { one = newOne; } public int getOne() { return one; } public boolean isGreater(BoolTest other) { /* missing code */ } } The isGreater method is intended to return true if the value of one for this BoolTest object is greater than the value of one for the BoolTest parameter other, and false otherwise. The following code segments have been proposed to replace /* missing code */. I. return one > other.one; II. return one > other.getOne(); III. return getOne() > other.one; Which of the following replacements for /* missing code */ can be used so that isGreater will work as intended?

I, II and III

Consider the following class definition. public class Person { private String name; public Person (String n) { name = n; } public void printStats() { System.out.println(this); } public String toString() { return "Hello " + name; } } Suppose you had the following code in a client class: Person p1 = new Person("Bibi"); p1.printStats(); What would be printed?

Hello Bibi

public class Widget { private int value; public Widget (int v) { value = v; } public int getValue() { return value; } public boolean isLess(Widget other) { /* missing code */ } } The isLess method is intended to return true if the value for this Widget object is less than the value for the Widget parameter other, and false otherwise. The following code segments have been proposed to replace /* missing code */. I. return value < other.value; II. return value < other.getValue (); III. return getValue() < other.value; Which of the following replacements for /* missing code */ can be used so that isLess will work as intended?

I, II, and III

Consider the following class definition. Each object of the class Employee will store the employee's name as name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate. public class Employee { private String name; private int wk_hours; private double pay_rate; public Employee(String nm, int hrs, double rt) { name = nm; wk_hours = hrs; pay_rate = rt; } public Employee(String nm, double rt) { name = nm; wk_hours = 20; pay_rate = rt; } } Which of the following code segments, found in a class other than Employee, could be used to correctly create an Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour? I. Employee e1 = new Employee("Lili", 20, 18.5); II. Employee e2 = new Employee("Steve", 18.5); III. Employee e3 = new Employee("Carol", 20);

I and II only

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. public class Item { private String itemName; private double regPrice; private double discountPercent; public Item (String name, double price, double discount) { itemName = name; regPrice = price; discountPercent = discount; } public Item (String name, double price) { itemName = name; regPrice = price; discountPercent = 0.25; } /* Other methods not shown */ } 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% ? I. Item b = new Item("blanket", 10.0, 0.25); II. Item b = new Item("blanket", 10.0); III. Item b = new Item("blanket", 0.25, 10.0);

I and II only

public static void multTwo(Fraction f) { f.setNum(2*f.getNum()); } Fraction val = new Fraction(3, 7); multTwo(val); System.out.println(val);

It will print out 6/7 When an OBJECT is passed to a method, a copy of the REFERENCE of the actual parameter is transferred to the formal parameter. Strings do not behave this way because they are immutable

Consider the class definition below. The method levelUp is intended to increase a Superhero object's strength attribute by the parameter amount. The method does not work as intended. public class Superhero { private String name; private String secretIdentity; private int strength; public Superhero(String realName, String codeName) { name = realName; secretIdentity = codeName; strength = 5; } public int levelUp(int amount) // line 14 { strength += amount; // line 16 } } Which of the following changes should be made so that the levelUp method works as intended? In line 14, levelUp should be declared as type void. In line 14, amount should be declared as type void. Line 16 should be changed to strength + amount;. Line 16 should be changed to return strength + amount;. Line 16 should be changed to return amount;.

In line 14, levelUp should be declared as type void.

Consider the following class definition, which represents two scores using the instance variables score1 and score2. The method reset is intended to set to 0 any score that is less than threshold. The method does not work as intended. public class TestClass { private int score1; private int score2; public TestClass(int num1, int num2) { score1 = num1; score2 = num2; } public void reset(int threshold) { if (score1 < threshold) // line 14 { score1 = 0; // line 16 } else if (score2 < threshold) // line 18 { score2 = 0; } } } Which of the following changes can be made so that the reset method works as intended? In lines 14 and 18, change < to >. In lines 14 and 18, change < to <=. In line 16, change score1 to num1 and in line 18, change score2 to num2. In line 18, change else if to if. In line 18, change else if to else.

In line 18, change else if to if.

Consider the following class, which models a bank account. The deposit method is intended to update the account balance by a given amount; however, it does not work as intended. public class BankAccount { private String accountOwnerName; private double balance; private int accountNumber; public BankAccount(String name, double initialBalance, int acctNum) { accountOwnerName = name; balance = initialBalance; accountNumber = acctNum; } public void deposit(double amount) { double balance = balance + amount; } } What is the best explanation of why the deposit method does not work as intended? The deposit method must have a return statement. In the deposit method, the variable balance should be replaced by the variable initialBalance. In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance. The method header for the deposit method should be public void deposit(amount). The variable balance must be passed to the deposit method.

In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance.

Consider the following partial class declaration. public class SomeClass { private int myA; private int myB; private int myC; //Constructor(s) not shown public int getA( ) { return myA; } public void setB(int value) { myB = value; } } Which of the following changes to SomeClass will allow other classes to access but not modify the value of myC ? Make myC public. Include the method: public int getC() { return myC; } Include the method: private int getC() { return myC; } Include the method: public void getC(int x) { x = myC; } Include the method: private void getC(int x) { x = myC; }

Include the method: public int getC() { return myC; }

public static void multTwo(Fraction f) { f = new Fraction(f); f.setNum(2*f.getNum()); } Fraction val = new Fraction(3, 7); multTwo(val); System.out.println(val);

It will print out 3/7 A copy of the REFERENCE of the actual parameter is still transferred to the formal parameter. However f is immediately assigned a NEW reference that has a copy of the old value using Fraction's copy constructor

public static void addTwo(int x) { x = x+2; } int val = 5; addTwo(val); System.out.print(val)

It will print out 5 When a primitive data type (int, double, char, etc.) is passed to a method, a copy of the VALUE of the actual parameter is transferred to the formal parameter. The value of 5 is copied to x, so x changes to 7. But, val is unaffected by anything that happens to x.

Consider the following class definition. The method appendIt is intended to take the string passed as a parameter and append it to the instance variable str. For example, if str contains "week", the call appendIt("end") should set str to "weekend". The method does not work as intended. public Class StringThing { private String str; public StringThing(String myStr) { str = myStr; } public void appendIt(String s) // line 10 { str + s; // line 12 } } Which of the following changes should be made so that the appendIt method works as intended? In line 10, the appendIt method should be declared as return type String. Line 12 should be changed to str = s + str;. Line 12 should be changed to str = str + s;. Line 12 should be changed to return s + str;. Line 12 should be changed to return str + s;.

Line 12 should be changed to str = str + s;.

A programming paradigm that uses classes

Object Oriented Programming (OOP)

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. public class Toy { private String name; private double price; public Toy(String n, double p) { name = n; price = p; } public void raisePrice(double surcharge) // Line 12 { return price + surcharge; // Line 14 } Which of the following changes should be made so that the class definition compiles without error and the method raisePrice works as intended? Replace line 14 with: surcharge += price; Replace line 14 with: price += surcharge ; Replace line 14 with: return price += surcharge;. Replace line 12 with: public raisePrice (double surcharge). Replace line 12 with: public double raisePrice (double surcharge).

Replace line 14 with: price += surcharge ;

Consider the following class declaration. The changeWeather method is intended to update the value of the instance variable weather and return the previous value of weather before it was updated. public class WeatherInfo { private String city; private int day; private String weather; public WeatherInfo(String c, int d, String w) { city = c; day = d; weather = w; } public String changeWeather(String w) { /* missing code */ } } Which of the following options should replace /* missing code */ so that the changeWeather method will work as intended? String prev = w; return weather; String prev = weather; return w; String prev = w; return prev; weather = w; String prev = weather; return prev; String prev = weather; weather = w; return prev;

String prev = weather; weather = w; return prev;

Consider the following definition of the class Student. public class Student { private int grade_level; private String name; private double GPA; public Student (int lvl, String nm, double gr) { grade_level = lvl; name = nm; GPA = gr; } } Which of the following object initializations will compile without error? Student max = new Student ("Max", 10, 3.75); Student max = new Student (3.75, "Max", 10); Student max = new Student (3.75, 10, "Max"); Student max = new Student (10, "Max", 3.75); Student max = new Student (10, 3.75, "Max");

Student max = new Student (10, "Max", 3.75);

Consider the following class definition. public class Pet { private String name; private int age; public Pet(String str, int a) { name = str; age = a; } public getName() { return name; } } Which choice correctly explains why this class definition fails to compile? The class is missing a mutator method. The class is missing an accessor method. The accessor method is missing a return type. The accessor method returns a variable other than an instance variable. The instance variables should be designated public instead of private.

The accessor method is missing a return type.

Consider the following class definition. public class Something { private static int count = 0; public Something() { count += 5; } public static void increment() { count++; } } The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment(); 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 class Something, not on the class itself. The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 1. The code segment creates a Something object s. The class Something's static variable count is 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 count value of 1. The code segment creates a Something object s. After executing the code segment, the object s has a count value of 5.

The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

The following class is used to represent shipping containers. Each container can hold a number of units equal to unitsPerContainer. public class UnitsHandler { private static int totalUnits = 0; private static int containers = 0; private static int unitsPerContainer = 0; public UnitsHandler(int containerSize) { unitsPerContainer = containerSize; } public static void update(int c) { containers = c; totalUnits = unitsPerContainer * containers; } } The following code segment appears in a method in a class other than UnitsHandler. Assume that no other code segments have created or modified UnitsHandler objects. UnitsHandler large = new UnitsHandler(100); UnitsHandler.update(8); Which of the following best describes the behavior of the code segment? The code segment does not compile, because it is not possible to create the object large from outside the UnitsHandler class. The code segment does not compile, because it attempts to change the values of private variables from outside the UnitsHandler class. The code segment does not compile, because the update method should be called on the object large instead of on the UnitsHandler class. The code segment creates a UnitsHandler object called large and sets the static variable unitsPerContainer to 100. The static variables containers and totalUnits each retain the default value 0. The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

Consider the following class definition. public class Gadget { private static int status = 0; public Gadget() { status = 10; } public static void setStatus(int s) { status = s; } } The following code segment appears in a method in a class other than Gadget. Gadget a = new Gadget(); Gadget.setStatus(3); Gadget b = new Gadget(); Which of the following best describes the behavior of the code segment? The code segment does not compile because the setStatus method should be called on an object of the class Gadget, not on the class itself. The code segment does not compile because the static variable status is not properly initialized. The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has a status value of 3 and the object b has a status value of 3. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has a status value of 3 and the object b has a status value of 10.

The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10.

Consider the following class definition. public class Thing { private static int value = 0; public Thing () { value = 7; } public static void setValue(int v) { value = v; } } The following code segment appears in a method in a class other than Thing. Thing a = new Thing (); Thing.setValue(4); Thing b = new Thing (); Which of the following best describes the behavior of the code segment? The code segment does not compile because the setValue method should be called on an object of the class Thing, not on the class itself. The code segment does not compile because the static variable value is not properly initialized. The code segment creates two Thing objects a and b. The class Thing static variable value is set to 7, then to 4, and then back to 7. The code segment creates two Thing objects a and b. After executing the code segment, the object a has a value of 4 and the object b has a value of 4. The code segment creates two Thing objects a and b. After executing the code segment, the object a has a value of 4 and the object b has a value of 7.

The code segment does not compile because the setValue method should be called on an object of the class Thing, not on the class itself.

Consider the following class declaration. public class Student { private String firstName; private String lastName; private int age; public Student(String firstName, String lastName, int age) { firstName = firstName; lastName = lastName; age = age; } public String toString() { return firstName + " " + lastName; } } The following code segment appears in a method in a class other than Student. It is intended to create a Student object and then to print the first name and last name associated with that object. Student s = new Student("Priya", "Banerjee", -1); System.out.println(s); Which of the following best explains why the code segment does not work as expected? The code segment will not compile because an object cannot be passed as a parameter in a call to println. The code segment will not compile because firstName, lastName, and age are names of instance variables and cannot be used as parameter names in the constructor. The code segment will not compile because the constructor needs to ensure that age is not negative. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the instance variables inside the constructor. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

Consider the following class. public class Help { private int h; public Help(int newH) { h = newH; } public double getH() { return h; } } The getH method is intended to return the value of the instance variable h. The following code segment shows an example of creating and using a Help object. Help h1 = new Help(5); int x = h1.getH(); System.out.println(x); Which of the following statements best explains why the getH method does not work as intended? The getH method should have a double parameter. The getH method should have an int parameter. The getH method should return newH instead of h. The getH method should have a return type of int. The getH method should have a return type of void.

The getH method should have a return type of int.

Consider the following class declaration. public class Student { private String name; private int age; public Student(String n, int a) { name = n; age = a; } public boolean isOlderThan5() { if (age > 5) { return true; } } } Which of the following best describes the reason this code segment will not compile? The return type for the isOlderThan5 method should be void. The return type for the isOlderThan5 method should be String. The return type for the isOlderThan5 method should be int. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5. The isOlderThan5 method should receive the variable age as a parameter.

The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.

Consider the following class definition. public class Password { private String password; public Password (String pwd) { password = pwd; } public void reset(String new_pwd) { password = new_pwd; } } Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile. Password p = new Password("password"); System.out.println("The new password is " + p.reset("password")); Which of the following best identifies the reason the code segment does not compile? The code segment attempts to access the private variable password from outside the Password class. The new password cannot be the same as the old password. The Password class constructor is invoked incorrectly. The reset method cannot be called from outside the Password class. The reset method does not return a value that can be printed.

The reset method does not return a value that can be printed.

Consider the following class definition. public class ItemInventory { private int numItems; public ItemInventory(int num) { numItems = num; } public updateItems(int newNum) { numItems = newNum; } } Which of the following best identifies the reason the class does not compile? The constructor header is missing a return type. The updateItems method should be declared as type void. The constructor should not have a parameter. The updateItems method should not have a parameter. The instance variable numItems should be public instead of private.

The updateItems method should be declared as type void.

Consider the following class definition. public class FishTank { private double numGallons; private boolean saltWater; public FishTank(double gals, boolean sw) { numGallons = gals; saltWater = sw; } public double getNumGallons() { return numGallons; } public boolean isSaltWater() { if (saltWater) { return "Salt Water"; } else { return "Fresh Water"; } } } Which of the following best explains the reason why the class will not compile? The variable numGallons is not declared in the getNumGallons method. The variable saltWater is not declared in the isSaltWater method. The isSaltWater method does not return the value of an instance variable. The value returned by the getNumGallons method is not compatible with the return type of the method. The value returned by the isSaltWater method is not compatible with the return type of the method.

The value returned by the isSaltWater method is not compatible with the return type of the method.

The class Worker is defined below. The class includes the method getEarnings, which is intended to return the total amount earned by the worker. public class Worker { private double hourlyRate; private double hoursWorked; private double earnings; public Worker(double rate, double hours) { hourlyRate = rate; hoursWorked = hours; } private void calculateEarnings() { double earnings = 0.0; earnings += hourlyRate * hoursWorked; } public double getEarnings() { calculateEarnings(); return earnings; } } 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. Worker bob = new Worker(20.0, 40.0); System.out.println(bob.getEarnings()); Which of the following best explains why an incorrect value is printed? The private variables hourlyRate and hoursWorked are not properly initialized. The private variables hourlyRate and hoursWorked should have been declared public. The private method calculateEarnings should have been declared public. The variable earnings in the calculateEarnings method is a local variable. The variables hourlyRate and hoursWorked in the calculateEarnings method are local variables.

The variable earnings in the calculateEarnings method is a local variable.

Consider the following class definition. public class Info { private String name; private int number; public Info(String n, int num) { name = n; number = num; } public void changeName(String newName) { name = newName; } public int addNum(int n) { num += n; return num; } } Which of the following best explains why the class will not compile? The class is missing an accessor method. The instance variables name and number should be designated public instead of private. The return type for the Info constructor is missing. The variable name is not defined in the changeName method. The variable num is not defined in the addNum method.

The variable num is not defined in the addNum method.

Consider the following class definition. public class ClassP { private String str; public ClassP(String newStr) { String str = newStr; } } The ClassP constructor is intended to initialize the str instance variable to the value of the formal parameter newStr. Which of the following statements best describes why the ClassP constructor does not work as intended? The constructor should have a return type of String. The constructor should have a return type of void. The instance variable str should be designated public. The variable str should be designated public in the constructor. The variable str should not be declared as a String in the constructor.

The variable str should not be declared as a String in the constructor.

Match each statement with what best describes it (assume standard naming convention is used) lancers Lancers() LANCERS lancers() Lancers

Variable Constructor Constant Method Class

Assume lhs is an instance within the School class. Match each of the following code statements(left) with the description(right) that best describes how name or name() would need to be written in the School class to to not cause an error in a client/driver class. (The line of the code on the left is to be executed from the main() method in a client/driver class) School.name(); School.name; School.name(2.789); School lhs = new School(); lhs.name(); lhs.name(1992 , "mustangs"); lhs.name;

a public static method a public static field a public static method a constructor a public, non-static(instance) method a public, non-static(instance) method a public, non-static(instance) field

A method that returns the value of a field

accessor

A structure for defining objects

class

A method that has the same name as its class

constructor

Consider the following class definition. public class Email { private String username; public Email(String u) { username = u; } public void printThis() { System.out.println(this); } public String toString() { return username + "@example.com"; } } The following code segment appears in a method in another class. Email e = new Email("default"); e.printThis(); What, if anything, is printed as a result of executing the code segment? e default [email protected] [email protected] Nothing is printed because the class will not compile.

[email protected]

The principle behind "instance variables should be private"

encapsulation

Consider the following class. The method getTotalSalaryAndBonus is intended to return an employee's total salary with the bonus added. The bonus should be doubled when the employee has 10 or more years of service. public class Employee { private String name; private double salary; private int yearsOfService; public Employee(String n, double sal, int years) { name = n; salary = sal; yearsOfService = years; } public double getTotalSalaryAndBonus(double bonus) { /* missing code */ } } Which of the following could replace /* missing code */ so that method getTotalSalaryAndBonus will work as intended? if (years >= 10) { bonus *= 2; } return salary + bonus; if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus; return salary + bonus; if (years >= 10) { bonus *= 2; } return sal + bonus; if (yearsOfService >= 10) { bonus *= 2; } return sal + bonus;

if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus;

One class derives properties from another class

inheritance

Making a new object of a class

instantiation

A method that changes the value of a field

modifier/mutator

public class Snack { private String name; private static int numSold = 0; public Snack (String n) { name = n; } public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the name and numSold variables? Both name and numSold can be accessed, but only name can be updated. Both name and numSold can be accessed, but only numSold can be updated. numSold can be accessed but not updated; name cannot be accessed or updated. numSold can be accessed and updated; name cannot be accessed or updated. Both name and numSold can be accessed and updated.

numSold can be accessed and updated; name cannot be accessed or updated.

Consider the following class definition. public class Beverage { private int numOunces; private static int numSold = 0; public Beverage(int numOz) { numOunces = numOz; } public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the numOunces and numSold variables? Both numOunces and numSold can be accessed and updated. Both numOunces and numSold can be accessed, but only numOunces can be updated. Both numOunces and numSold can be accessed, but only numSold can be updated. numSold can be accessed but not updated; numOunces cannot be accessed or updated. numSold can be accessed and updated; numOunces cannot be accessed or updated.

numSold can be accessed and updated; numOunces cannot be accessed or updated.

The Thing class below will contain a String attribute, a constructor, and the helper method, which will be kept internal to the class. public class Thing { /* missing code */ } Write a correct Implementation of the class

private String str; public Thing(String s) { /* implementation not shown */ } private void helper() { /* implementation not shown */ }

Properties/behaviors that are directly accessible only in the code of the same class

private fields and methods

The Fraction class below will contain two int attributes for the numerator and denominator of a fraction. The class will also contain a method fractionToDecimal that can be accessed from outside the class. public class Fraction { /* missing code */ // constructor and other methods not shown } Write a correct implementation of the class

private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

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. public class Player { /* missing code */ } Write the correct implementation for this class

private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ }

Consider the following class definition. public class Person { private String name; /* missing constructor */ } The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington"); Which of the following can be used to replace /* missing constructor */ so that the object p is correctly created? private Person() { name = n; } private Person(String n) { name = n; } public Person() { name = n; } public Person(String n) { name = n; } public Person(String name) { String n = name; }

public Person(String n) { name = n; }

Consider the following class definition. public class RentalCar { private double dailyRate; // the fee per rental day private double mileageRate; // the fee per mile driven public RentalCar(double daily, double mileage) { dailyRate = daily; mileageRate = mileage; } public double calculateFee(int days, int miles) { /* missing code */ } } 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? return dailyRate + mileageRate; return (daily * dailyRate) + (mileage * mileageRate); return (daily * days) + (mileage * miles); return (days * dailyRate) + (miles * mileageRate); return (days + miles) * (dailyRate + mileageRate);

return (days * dailyRate) + (miles * mileageRate);

Properties/behaviors associated with an entire class(not with individual objects)

static fields and methods


संबंधित स्टडी सेट्स

Academic Team Full Practice Set 8

View Set

chapter 12: antimicrobial treatment

View Set

Chapter 47: Caring for Clients with Disorders of the Liver, Gallbladder, or Pancreas

View Set

Pharmacology: Alternative Methods for Drug Administration

View Set