Chapter ONE
Encapsulation and Immutable Classes

Exam Objectives

Implement encapsulation.
Override hashCode, equals, and toString methods from Object class.
Create and use singleton classes and immutable classes.
Develop code that uses static keyword on initialize blocks, variables, methods, and classes.
Develop code that uses final keyword.

Answers

1. The correct answer is D.
As a final attribute, a is required to have been initialized, so compilation fails on the line marked as // 3.


2. The correct answer is D.
Private is the most restrictive of all access modifiers. public is the least restrictive of all.

Between default and protected, the latter is less restrictive since even if a subclass belongs to another package than the superclass, it can access protected members, in contrast to the default access (which has a same-package only level).


3. The correct answer is C.
As a final variable, n must be initialized either when declared, in a constructor, or a block. This, and the fact that changing its value is not allowed (in the setter method) generates a compile-time error.


4. The correct answer is A.
Although attribute list is final, this keyword only makes its reference immutable; it cannot be assigned another object (like a new List), but the values inside the object can change (if they are not final themselves). This (and other details) makes the class mutable.


5. The correct answer is B.
Attribute s is private, however, since the main method is in the same class, it can use the attribute without any problem.


6. The correct answer is D.
Attribute b is not static. A static block cannot reference a non-static variable. That's the reason compilation fails.