Constructors
With the same name as the class and no return value, used to initialize class properties;
The constructor is also divided into the parameterless constructor and the parametric constructor.
1.1: No parameter constructor
public class contruction{//... Properties ... public contruction () {}//No parameter constructor, no write, the system will automatically add}
1.2: A parametric constructor
public class Contruction {private int i; public contruction (int i) {/* has a parameter constructor, if you define a constructor with parameters, you must have parameters when instantiating the object, otherwise you will get an error because you created a parameter, Then you know exactly what you're doing. The system does not automatically add the parameterless constructor */this.i = i; }}
Building Code Blocks
An instantiation of an object executes once per instantiation;
The code block is constructed in the following format:
public class Contruction {public contruction () { System.out.pintln ("I am a constructor method"); } { System.out.pintln ("I am Building code block"); } public static void Main (String args[]) { contruction c1=new contruction (); contruction c2=new contruction (); } }
Results:
As you can see from the results, constructing code blocks takes precedence over constructors.
Static code block
Class loading executes, regardless of the number of new objects, executed only once;
public class Contruction {public contruction () { System.out.println ("I am a constructor method"); } static { System.out.println ("I am a static code block. No matter how many instances of new, I only execute once "); } public static void Main (String args[]) { contruction c1 = new contruction (); contruction C2 = new contruction ();} }
Results:
As you can see from the results, the static code block executes only once and takes precedence over the constructor execution.
No inherited initialization order:
Static member variables, static code blocks >> Normal member variables, plain code blocks >> constructors
Has an inherited initialization order:
Parent class static member variable, parent class static code block >> subclass static member variable, static code block >> parent class normal member variable, parent class code block >> parent class constructor >> subclass ordinary member variable, subclass generic code Blocks >> sub-class constructors
Java constructors, building blocks of code, execution order of static code blocks