Skip to content

Instantly share code, notes, and snippets.

@jelinski
Created March 19, 2018 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jelinski/2f4b8484b44e90f5081231d6d4e41567 to your computer and use it in GitHub Desktop.
Save jelinski/2f4b8484b44e90f5081231d6d4e41567 to your computer and use it in GitHub Desktop.
Initialization blocks order in Java. Especially useful for anonymous classes in order to mimic constructor behavior
package pl.jellysoft;
public class Main {
public static void main(String[] args) {
// Create anonymous class
new Child() {
/* THIS WON'T COMPILE
static{
System.out.println("Static initializer block within Example");
}
*/
{
System.out.println("Initializer block within Anonymous class");
childMethod();
parentMethod();
}
private void newMethod() {
System.out.println("Method from anonymous class invoked");
}
}.newMethod();
}
private static class Child extends Parent {
static {
System.out.println("Static initializer block within Child class");
}
{
System.out.println("Initializer block within Child class");
}
Child() {
System.out.println("Inside Child class constructor");
}
void childMethod() {
System.out.println("Child method invoked");
}
}
private static class Parent {
static {
System.out.println("Static initializer block within Parent class");
}
{
System.out.println("Initializer block within Parent class");
}
Parent() {
System.out.println("Inside Parent class constructor");
}
void parentMethod() {
System.out.println("Parent method invoked");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment