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?
Let us walk through the order of execution:
new d() creates an object of d, it needs to invoke super().b.b will invoke the method b but since there is an overridden method available in class d, it will be invoked.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With