Created
April 24, 2017 04:39
-
-
Save louy2/14dfb9a1f88bc1474bbdb072113fe48e to your computer and use it in GitHub Desktop.
Solving A Java Inheritance Puzzler from https://llogiq.github.io/2015/07/14/inheritance.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Solving A Java Inheritance Puzzler from | |
* https://llogiq.github.io/2015/07/14/inheritance.html | |
*/ | |
class A { | |
int x = 3; | |
int a() { x++; return x + c(); } | |
int b() { return a(); } | |
int c() { return x; } | |
} | |
class B extends A { | |
@Override int a() { return super.a() + c(); } | |
} | |
class C extends B { | |
@Override int b() { return a() * 3; } | |
@Override int c() { return x + 1; } | |
} | |
public class E { | |
public static void main(String[] args) { | |
int x = new C().b(); | |
/* | |
* Because C overrides b(), x = a() * 3 | |
* C inherits B, which overrides a(), so a() = A.a() + c() | |
* x = (A.a() + c()) * 3 | |
* Which c() is it? A.c() or C.c()? | |
* Without super, it is this.c(), and this == C() | |
* x = (A.a() + C.c()) * 3 | |
* A.a() is x + 1 + c(), which c() is that? | |
* By the same logic, C.c() | |
* x = (x + 1 + C.c() + C.c()) * 3 | |
* x = (x + 1 + x + 1 + x + 1) * 3 | |
* x = (3 + 1 + 3 + 1 + 3 + 1) * 3 | |
* x = 12 * 3 = 36 | |
*/ | |
System.out.println(x); // Wrong! x = 42 | |
/* | |
* Override analysis was correct. | |
* Mutable state analysis was wrong. | |
* Assumption that x++ translate to x+1 is wrong. | |
* (Been programming pure functional too long?) | |
* C.b() -> B.a() * 3 x = 3 | |
* B.a() -> A.a() + C.c() x = 3 | |
* A.a() -> x + C.c() x = 4 | |
* C.c() -> 5 x = 4 | |
* A.a() -> 9 x = 4 | |
* B.a() -> 14 x = 4 | |
* C.b() -> 42 x = 4 | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment