Java-4.6 member Initialization
In this section, we will discuss the initialization of members.
As mentioned earlier, if it is an attribute field, the compiler will initialize it by default. This section will not be expanded. here we need to note the local variables.
Local variables must be initialized. Otherwise, an error is reported.
The following is the error code:
package com.ray.ch01;public class Test {public static void main(String[] args) {int i;i++;}}
In I ++, the compiler prompts that no initialization variable exists.
1. Specify variable Initialization
The following describes several initialization methods.
(1) Direct initialization, directly assigning values to attribute Fields
package com.ray.ch01;public class Test {private int id=0;}
(2) return via Method
package com.ray.ch01;public class Test {private int id = initId();private int initId() {return 0;}}
package com.ray.ch01;public class Test {private int id = initId(0);private int initId(int id) {return id;}}
(3) initialize with new
package com.ray.ch01;public class Test {private Book book = new Book();}class Book {}
If you do not create a book object, you can directly use it. An exception is thrown during running.
(4) Pay attention to the execution sequence and ensure that the parameter members have been initialized.
Correct code:
package com.ray.ch01;public class Test {private int id = initId();private int initId() {return 0;}private String name = initName(name-+id);private String initName(String name) {return name;}}
Error code:
package com.ray.ch01;public class Test {private String name = initName(name-+id);private String initName(String name) {return name;}private int id = initId();private int initId() {return 0;}}
The two codes are exactly the same, but the location is changed. In the error code, the id reports an error and the id is not initialized.
Summary: This chapter discusses Member initialization, especially local variables and initialization methods.