Java Magazine, Jan/Feb 2018
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2018 106 fix this Answers Answer 1 The correct answers are options B and C Java Language Specification section 8312 says this about final fields A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared or a compile time error occurs This means that the final field x must receive exactly one explicit assignment which must happen before the constructor is complete This tells you immediately that option A must be incorrect because in the original code presented in the question there is no assignment to the field Note that the field as declared is termed a blank final the terminology used in the Java specification paragraph above and as such the default assignment to zero that is implicit for all object members does not satisfy the requirement Change 1 assigns a value to x as part of its declaration and therefore x is definitely assigned even before any constructor runs Therefore option B is correct Change 2 adds a simple constructor that initializes the value of x This change made in isolation would result in exactly one constructor and causes that constructor to unconditionally assign a value to x Because the blank final is definitely assigned exactly once before the end of the only constructor this change works and option C is correct Change 3 suggests adding a constructor that might seem functionally equivalent to the one proposed in change 2 However in this case the change fails The private method that attempts to assign the value to x will not compile because its possible for it to be invoked after the object has been initialized Because this fails to compile option D must be incorrect Performing both change 1 and change 2 also fails because this would result in an attempt to perform two assignments to the variable x and the Java specification demands exactly one assignment Therefore option E is also incorrect
You must have JavaScript enabled to view digital editions.