Skip to content

Instantly share code, notes, and snippets.

@beoliver
Last active August 29, 2015 14:19
Show Gist options
  • Save beoliver/d4e350d5f69c33c8c450 to your computer and use it in GitHub Desktop.
Save beoliver/d4e350d5f69c33c8c450 to your computer and use it in GitHub Desktop.
// nested classes | static classes
public class Main {
public static void main(String[] args) {
Outer a = new Outer(6);
Outer.InnerB b1 = a.new InnerB();
Outer.InnerB b2 = new Outer(7).new InnerB();
Outer.InnerC c1 = new Outer.InnerC(8);
b1.printOuterValue();
b2.printOuterValue();
c1.printValue(); // as InnerC is static, we can never ref values of the parent
}
}
class Outer {
private int a;
public Outer(int a) {
this.a = a;
}
class InnerB {
int b;
public InnerB() {
this.b = a; // works as we need to create new Outer before new Inner
}
public void printOuterValue() {
// works as y is within our scope
System.out.println(a);
}
}
static class InnerC {
private int c;
public InnerC(int c) {
this.c = c;
}
public void printValue() {
System.out.println(c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment