ProgrammingHardProduct-company placement · Java

Which constructors cause compile-time errors?

Which constructors cause compile-time errors?
class F {
    final int x;
    F() { }                          // constructor 1
    F(int v) { x = v; x = v + 1; }   // constructor 2
}
  1. A. Only constructor 1
  2. B. Only constructor 2
  3. C. Both constructors
  4. D. Neither; x defaults to 0

Correct answer: C. Both constructors

A blank final field must be definitely assigned exactly once by the end of every constructor: constructor 1 never assigns it, constructor 2 assigns it twice.

More OOP with C++ and Java questions

Exams that ask this topic