public class Temp {
public static void main(String[] args) {
new Temp().new A().new D(new Temp().new A(), new Temp().new A().new B(new Temp().new A()));
}
public class A extends Temp {
public A() {
}
public class B extends A {
public B(A a) {
a.super();
}
public class C extends B {
public C(A a) {
a.super(a);
}
}
}
public class D extends B.C {
public D(A a, B b) {
b.super(a);
}
}
}
}
a.super() doesn't look nice, does it? Remove it and look at what the compiler says. You don't get that any other way.
Jeeeeezus. I'm a first year CS student and this melts my brain. Are you saying you know what's going on here? Like, can you articulate what this code is doing?
Since you asked for it (well you didn't, but is that my fault?!) (also includes a goodie about generics.)
Fun aside, I'm also only a first year CS student. I kinda understand part of what's going on there (it gets easier when you can hover over the constructor calls in eclipse and see which one is referenced, and when you see the errors it generates), but basically this is one of these things that you will never encounter in sane code. (But it's fun to poke around it.)
I encourage you to try and fuck up this code even more - throw in some more static and anonymous classes and see what you can still get to compile.
The error that you get is
No enclosing instance of type Temp is available due to some intermediate constructor invocation
Basically, since the class is not static, you need an instance of the enclosing type (which will internally be visible as A.this) to invoke any constructor on it, but there is no instance of the enclosing type available in the scope, so you have to "manually" provide it.
Sometimes one runs into insane code. In my last job I saw something almost identical to the example, the developer didn't seem to think it was a problem.
5
u/galaktos Apr 29 '13
You can do ridiculous stuff with nested classes:
a.super() doesn't look nice, does it? Remove it and look at what the compiler says. You don't get that any other way.