The following two classes are in different packages:
package shop; public class Item { private double price; int stock; protected String sku; public String label; public double getPrice() { return price; } void restock(int n) { stock += n; } }
package app; import shop.Item; public class Checkout { public void run(Item it) { String a = it.label; int b = it.stock; String c = it.sku; double d = it.price; double e = it.getPrice(); it.restock(5); } }
How many of the six statements in run fail to compile because of access rules? Give your answer as a whole number.
Unlock full course notes by signing up
Reading another object's private field
Consider the following class:
A separate class runs System.out.println(new Point(2, 3).sameAs(new Point(2, 3)));. What happens?
Access rules when overriding methods
A class Account declares three methods: protected double fee(), public String id() and private void audit(). The class SavingsAccount extends Account is in the same package, and it declares its own fee(), id() and audit() with the same signatures. Fill in each blank with one word.
Because fee() is protected in Account, the overriding fee() in SavingsAccount may be declared protected or ________. Because id() is public in Account, its override must be declared ________.
If SavingsAccount declares fee() with no access modifier, the result is a compile-time ________, even though both classes are in the same package. Because audit() is private, SavingsAccount does not ________ it, so the audit() in SavingsAccount is a new, separate method and may use any access level.
Choosing the most restrictive modifier
The class Thermostat is declared public in package home.climate. Its own methods use all of its members, and other classes use them as follows:
Field targetTemp: read and written only by Thermostat's own methods.
Method adjust(): called by Scheduler, another class in home.climate, and by no class outside that package.
Protected access through different reference types
Three Java classes are each in their own source file. Animal and Keeper are in package zoo.core; Lion is a subclass of Animal in package zoo.exhibits. Judge each labelled statement on its own, as if every other labelled statement were absent.
Give each answer as a whole number: the number of Keeper statements (K1 to K4) that compile, the number of Keeper statements that fail, the number of Lion statements (L1 to L7) that compile, and the number of Lion statements that fail.