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.
package zoo.core; public class Animal { protected int age; protected void feed() { } int tag; // no modifier private double weight; public String name; }
package zoo.core; public class Keeper { void visit(Animal a) { a.age = 2; // K1 a.feed(); // K2 a.tag = 9; // K3 a.weight = 50.0; // K4 } }
package zoo.exhibits; import zoo.core.Animal; public class Lion extends Animal { void check(Lion other, Animal generic) { age = 3; // L1 this.feed(); // L2 other.age = 4; // L3 generic.age = 5; // L4 generic.feed(); // L5 tag = 7; // L6 generic.name = "Leo"; // L7 } }
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.
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?
Counting access errors in a checkout class
The following two classes are in different packages:
How many of the six statements in run fail to compile because of access rules? Give your answer as a whole number.
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.