Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 3
Question ID: UKOCP39360
Given code:
- package com.udayankhattry.ocp;
- class Outer {
- private String name = "NOW OR NEVER";
- //Insert inner class definition here
- }
- public class Test {
- public static void main(String [] args) {
- new Outer().new Inner().printName();
- }
- }
Which of the following Inner class definitions inserted in the Outer class, will print NOW OR NEVER in the output on executing Test class?
Select 2 options.
-
A
- class Inner {
- public void printName() {
- System.out.println(this.name);
- }
- }
-
B
- class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
-
C
- inner class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
-
D
- abstract class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
-
E
- class Inner {
- public void printName() {
- System.out.println(Outer.this.name);
- }
- }
Reveal correct answers
Correct answers: B, E
Explanation
UKOCP39360:
Let's check all the options one by one:
- class Inner {
- public void printName() {
- System.out.println(this.name);
- }
- }
✗ Keyword 'this' inside Inner class refers to currently executing instance of Inner class and not the Outer class. As, there is no instance variable 'name' inside Inner class, hence this.name causes compilation error.
- class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
✓ To access Outer class variable from within inner class you can use these 2 statements: System.out.println(name); OR System.out.println(Outer.this.name);
- inner class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
✗ There is no keyword with the name 'inner' in java.
- abstract class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
✗ As new Inner() is used in main method, hence cannot declare class Inner as abstract in this case. But note that abstract or final can be used with regular inner classes.
- class Inner {
- public void printName() {
- System.out.println(Outer.this.name);
- }
- }
✓ To access Outer class variable from within inner class you can use these 2 statements: System.out.println(name); OR System.out.println(Outer.this.name);
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
