nerdexam
Oracle

1Z0-819 · Question #120

Given: public class A { private boolean checkValue(int val) { return true; } } and public class B extends A { public int modifyVal(int val) { if (checkValue(val)) { return val; } else { return 0; }…

The correct answer is B. Fails to compile. Option B is correct because checkValue is declared private in class A, meaning it is invisible outside of class A - including to subclasses. When class B calls checkValue(val), the Java compiler cannot resolve that method within B's scope and raises a compile-time error. E (10)…

Java Object-Oriented Approach

Question

Given: public class A { private boolean checkValue(int val) { return true; } } and public class B extends A { public int modifyVal(int val) { if (checkValue(val)) { return val; } else { return 0; } } } and public static void main(String[] args) { B b = new B(); System.out.println(b.modifyVal(10)); } What is the result?

Options

  • ANothing
  • BFails to compile.
  • C0
  • DA java.lang.IllegalArgumentException is thrown.
  • E10

How the community answered

(26 responses)
  • A
    15% (4)
  • B
    73% (19)
  • D
    4% (1)
  • E
    8% (2)

Explanation

Option B is correct because checkValue is declared private in class A, meaning it is invisible outside of class A - including to subclasses. When class B calls checkValue(val), the Java compiler cannot resolve that method within B's scope and raises a compile-time error. E (10) is wrong because even though checkValue always returns true, B never gets to call it - the code never compiles. C (0) is wrong for the same reason; return 0 requires the else branch to execute at runtime, which is impossible if compilation fails. A and D are wrong because both require the program to actually run - no output and no exception can be produced when the compiler rejects the code before execution.

Memory tip: Think of private as a vault that only the declaring class holds the key to - not even its own children can inherit it. When you see a subclass calling a private method from a parent, immediately flag it as a compile error.

Topics

#Access modifiers#Inheritance#Private methods#Compilation

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice