Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many different versions of 'x' are accessible in (*)?

This is a training exercise for understanding the workings of inner classes in Java. As the question states, how many different versions of x are accessible in (*)?

class Outer {     int x;      class Inner extends Outer {         int x;          void f(int x) {             (*)         }     } } 

I'm inclined to think that there are 3, namely: this.x, super.x and x but some of my peers seem to think that there are 4.

Which of us is confused? And can you explain?

like image 842
user43389 Avatar asked Jan 12 '16 23:01

user43389


2 Answers

There are 4, namely: x, this.x, super.x and Outer.this.x.

Consider the following:

public class Outer {      int x;      public static void main(String[] args) {         Outer outer = new Outer();         Outer.Inner inner = outer.new Inner();         outer.x = 3;         inner.x = 2;         inner.f(1);     }      class Inner extends Outer {         int x;          void f(int x) {             System.out.println(super.x);             System.out.println(x);             System.out.println(this.x);             System.out.println(Outer.this.x);         }     }  } 

This code will print

0 1 2 3 

showing 4 different values.

What's happening is the following:

  1. The parent of the inner instance has an unitialized x variable. For an int, the default value is 0: this is super.x.
  2. The method f is called with the argument 1: this is x.
  3. The instance inner was set its x to 2 with inner.x = 2: this is this.x.
  4. The outer instance, which is Outer.this was set its x value to 3: this is Outer.this.x.

The trick here is that Inner is both an inner class (so it has an enclosing Outer instance) and a subclass (so it has a parent Outer instance), and those two Outer instances are not the same.

like image 77
Tunaki Avatar answered Sep 21 '22 05:09

Tunaki


There are four of them:

  • Outer.this.x for the Outer class property
  • this.x for the Inner class property
  • super.x for the super type Outer class property
  • x for the method argument
like image 29
Younes Regaieg Avatar answered Sep 23 '22 05:09

Younes Regaieg