Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 79
Question ID: UKOCP61251
Given code:
- package com.udayankhattry.ocp;
- class P {
- private int var = 100;
- class Q {
- String var = "Java";
- void print() {
- System.out.println(var);
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- new P().new Q().print();
- }
- }
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.
