2

I have this code that appeared in a quiz

public class Main {
  public static void main(String[] args) {
    class b {
      int i = 32;
      b() { b(); }
      void b() { System.out.println(++i); }
    }

    class d extends b {
      int i = 8;
      d() {}
      void b() { System.out.println(--i); }
    }

    b b = new d();
  }
}

What should be the output? It turns out that the answer is -1 while I expected it to be 7. Is java broken?

Andreas
  • 55
  • 3

1 Answers1

14

Let us walk through the order of execution:

  1. Before new d() creates an object of d, it needs to invoke super().
  2. Control is transferred to the default constructor of b.
  3. Constructor of class b will invoke the method b but since there is an overridden method available in class d, it will be invoked.
  4. Note that the instance of b is not yet created and the value of i is hidden (d.i hides b.i) and hence the value of i is 0. So doing --i generates -1 as the output.
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • 1
    This is far superior to some of the dupes maybe you can consider also answering some of them in the same manner – dreamcrash Apr 07 '21 at 17:00