JAVA_SE basics -- 30. Construct code blocks
Blog for dark horse programmers...
Construct a code block: Initialize all objects in a unified manner.
Problem: Every child is asked to cry at birth. This code has two constructors. If you need to cry at birth for each child, you need to call cry () in different constructors () function, but this causes code duplication. How can this problem be solved? Construct a code block.
Class Perosn {private int id; // privatized int variable idprivate String name; // privatized String variable nameprivate int age; // privatized int variable age {cry (); // execute the code here when every Person object is created} public Perosn () {cry ();} public Perosn (int id, String name, int age) {// variable id, name, age initialization attribute this. id = id; this. name = name; this. age = age;} public int getId () {// access Idreturn id;} public void setId (int id) {// set idthis. id = id;} public String getName () {// access namereturn name;} public void setName (String name) {// set namethis. name = name;} public int getAge () {// access agereturn age;} public void setAge (int age) {// set agethis. age = age;} public void cry () {// cry System. out. println (Wow ....);}}
P.S.
1: Initialize the object. The object runs as soon as it is created and takes precedence over the constructor.
2: The difference between the Construction Code block and the constructor. The construction code block initializes all objects in a unified manner, and the constructor initializes the corresponding objects.
3: Construct a code block: It extracts public information from all constructor methods.
For example, when a child is born
Let's look at a complete example:
Class Boy {String name; int age; String gender; // construct a code block to initialize all objects. {System. out. println (crying ...);} Boy () {System. out. println (the parameter construction is being called);} Boy (String n, int a, String g) {name = n; age = a; gender = g; System. out. println (the parameter construction is being called);} void run () {System. out. println (run ...);}} class Demo {public static void main (String [] args) {Boy B = new Boy (); Boy b2 = new Boy (jack, 1, male );}}Running result:
Cry...
No parameter construction being called
Cry...
Parameter construction being called
Just differentiate them from constructors and remember their core functions:
Construct a code block: Construct a code block to initialize all objects in a unified manner.
Constructor: the constructor initializes the corresponding object.