Skip to content

Instantly share code, notes, and snippets.

@javajosh
Created July 6, 2011 00:59
Show Gist options
  • Save javajosh/1066314 to your computer and use it in GitHub Desktop.
Save javajosh/1066314 to your computer and use it in GitHub Desktop.
Static vs Inner vs Abstract classes in Java
package javajosh.hello;
public class Main {
//All children print out their names when they init
static class InitPrint {
{System.out.println(this.getClass().getName() + ": init()");}
}
static class StaticClassExample {
static class Parent extends InitPrint{
private static String value = "ParentValue";
private String childValue = ChildB.childBValue;
static class ChildA extends InitPrint{String parentAccess = value;}
static class ChildB extends InitPrint{private static String childBValue = "";}
static class ChildC extends InitPrint{String childBValue = Parent.ChildB.childBValue;}
}
void main(){
new Parent();
new Parent.ChildA();
new Parent.ChildB();
new Parent.ChildC();
}
}
static class InnerClassExample{
static class Parent extends InitPrint{
private String value = "ParentValue";
private ChildB childB = new ChildB();
private String childValue = childB.childBValue;
class ChildA extends InitPrint{String parentAccess = value + Parent.this.value;}
class ChildB extends InitPrint{private String childBValue = "childBValue";}
class ChildC extends InitPrint{String childBValue = Parent.this.childB.childBValue;}
}
void main(){
new Parent();
new Parent().new ChildA();
new Parent().new ChildB();
new Parent().new ChildC();
}
}
static class NastyExample{
static class Parent extends InitPrint{
static class ChildA extends InitPrint{
static class GrandChildA extends InitPrint{}
static class GrandChildB extends InitPrint{private String grandChildBValue = "grandChildBValue";}
static class GrandChildC extends InitPrint{}
}
static class ChildB extends InitPrint{}
static class ChildC extends InitPrint{void foo(ChildA.GrandChildB gcb){
System.out.println("Nephew Access of private value: " + gcb.grandChildBValue);
}}
}
void main(){
Parent.ChildA.GrandChildB gcb = new Parent.ChildA.GrandChildB();
Parent.ChildC cc = new Parent.ChildC();
cc.foo(gcb);
}
}
static class AnonymousClassExample{
static class Node extends InitPrint{
private String name;
Node(String name){this.name = name; System.out.println(name);}
void foo(Node n){System.out.println(n.name);}
}
void main(){
Node parent = new Node("parent"){
Node childA = new Node("childA"){};
Node childB = new Node("childB"){};
Node childC = new Node("childC"){};
{childC.foo(childB);} //yes, this works.
};
//parent.childA; //<-- you can't access anonymous members. which is actually really good behavior.
}
}
public static void main(String[] args) {
new StaticClassExample().main();
new InnerClassExample().main();
new NastyExample().main();
new AnonymousClassExample().main();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment