Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Easy
Question 23
Given code:
- package com.udayan.ocp;
- class Outer {
- private String name = "James Gosling";
- //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 definition inserted in the Outer class, will print 'James Gosling' in the output on executing Test class?
-
A
- inner class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
-
B
- class Inner {
- public void printName() {
- System.out.println(this.name);
- }
- }
-
C
- abstract class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
-
D
- class Inner {
- public void printName() {
- System.out.println(name);
- }
- }
Reveal correct answer
Correct answer: D
Explanation
Variable 'name' can be referred to, either by name or Outer.this.name. There is no keyword with the name 'inner' in java.
As new Inner() is used in the main method, hence cannot declare class Inner as abstract in this case. But note abstract or final can be used with regular inner classes.
Keyword 'this' inside the Inner class refers to the currently executing instance of the Inner class and not the Outer class.
To access the Outer class variable from within the 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.
