0

Which three code fragments, added individually at line 26, produce the output 100? (Choose three.)

class Inner {

private int x;

public void setX(int x) {this.x = x;}

public int getX(){return x;}
}

class Outer{

 private Inner y;

 public void setY(Inner y) {this.y = y;}

 public Inner getY(){return y;}

}

public class Gamma {

 public static void main(String[] args){

 Outer o = new Outer();

 Inner i = new Inner();

 int n = 10;

 i.setX(n);

 o.setY(i);

**// Line 26**

 System.out.println(o.getY().getX());

 }

 }

This question is from SCJP

A.
n = 100;

B.
i.setX( 100 );

C.
o.getY().setX( 100 );

D.
i = new Inner(); i.setX( 100 );

E.
o.setY( i ); 
i = new Inner(); 
i.setX( 100 );

F.
i = new Inner(); 
i.setX( 100 ); 
o.setY( i );

ANSWER IS BCF

I understand B and C but i dont understand F. If i use D option why its giving me 10 as output. I want to know what is happening when i use option D.

Ure replies are more than welcomed

Thanks in advance

java seeker
  • 1,246
  • 10
  • 13
user2985842
  • 437
  • 9
  • 24

2 Answers2

0

The only object that has a getX method is Inner. Outer exposes a setter to Inner, allowing you to set the reference that you want. The reference being passed in has a setX call with the value 100, hence the reason why it works.

To illustrate it with a bit of ASCII art...

Outer     Inner      int
+---+     +---+     +---+
| o | --- | y | --- | x |
+---+     +---+     +---+
  • You instantiate a reference of Inner.
  • You set the instance of Inner's int value to 100.
  • You place your reference of Inner inside of Outer. Inner's int value is still 100.
  • You then call o.getY().getX(), which retrieves the value of 100.
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

On your code at "line 25" the variable i and y refers to the same memory address, so if u take the option D, you will create a new object and i will point to a new memory adress, making any change to i to be independent of the first Inner object created and which variable y is still pointing

:D