The recent re-reading of the Java programming idea to read about the instantiation code block gives me a deeper understanding of how to initialize with two curly braces.
Instantiate a block of code:
and static code block the concept of the corresponding, static code block is the static keyword + curly braces, the static code block is removed from the passive keyword is instantiated code block, static code block at the time of class initialization execution
The instantiation code block executes each time the object is generated (the instantiation code block is executed prior to the construction method ).
Initialize with an anonymous inner class: At the time of the new object, the parentheses are followed by a curly brace
Use anonymous inner class + instantiation code block = Initialize with two curly braces
Examples are as follows:
Packagecom.jiaoyiping.thinking;Importjava.util.ArrayList;Importjava.util.List;/** Created with Intellij idea * USER: kj a flat * DATE:2015/10/25 * time:10:41 * To change this template use File | Settings | File Template*/ Public classTestinstancecodeblock { Public Static voidMainFinalstring[] args) { //Anonymous Inner classPerson person =NewPerson ("Zhang San") {@Override PublicString GetName () {return Super. GetName () + "123"; } }; System.out.println (Person.getname ()); //Two curly braces are initialized (essentially anonymous inner class + instantiation code block)List<string> personlist =NewArraylist<string>() {{Add ("AA"); Add ("BB"); Add ("CC"); }}; for(String s:personlist) {System.out.println (s); } }}classperson{String name; PublicPerson (String name) { This. Name =name; System.out.println ("Construction Method Execution ..."); } //instantiate a block of code before the construction method executes{System.out.println ("Instance initialization ..."); } PublicString GetName () {returnname; }}
An understanding of initialization using two curly braces in Java