Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy

Question 79

Question ID: UKOCP61251


Given code:


What will be the result of compiling and executing Test class?

  • A Java
  • B 100
  • C Compilation error
  • D Exception is thrown at runtime
Reveal correct answer

Correct answer: A

Explanation

UKOCP61251:

In this example, inner class's variable var shadows the outer class's variable var. So output is Java.


Few points to note here: 

1. If inner class shadows the variable of outer class, then Java compiler prepends 'this.' to the variable. System.out.println(var); is replaced by System.out.println(this.var);

2. If inner class does not shadow the variable of outer class, then Java compiler prepends "outer_class.this." to the variable. So, if class Q doesn't shadow the variable of class P, then System.out.println(var); would be replaced by System.out.println(P.this.var);


In the given example, if you provide System.out.println(P.this.var); inside print() method, then output would be 100.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need