Created
March 19, 2018 16:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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