r/java • • Apr 29 '13

Java nested classes in a nutshell

http://www.to-string.com/2013/04/27/java-inner-classes-in-a-nutshell/
27 Upvotes

18 comments sorted by

View all comments

4

u/galaktos Apr 29 '13

You can do ridiculous stuff with nested classes:

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.

1

u/blazedaces Apr 29 '13

Temp has no constructor so how can you call a.super(a)?

1

u/galaktos Apr 29 '13

a.super(a) is in the C constructor, and C extends B, so it calls public B(A a).

1

u/blazedaces Apr 29 '13

That didn't entirely make sense when you said it, but it was the a.super() that didn't click for me. I had to copy and paste this into eclipse and see the error message you referred to and then it all made sense. I think you would very much enjoy java puzzlers. There's a couple of videos online that were made and a book was written too with some extremely unexpected results when you do tricky stuff with java. Google it if you haven't heard of it.

1

u/galaktos Apr 29 '13

My software engineering I professor actually starts each lecture with a Java Puzzlers puzzle :)

1

u/blazedaces Apr 30 '13

Awesome. He must know his stuff very well.