In this chapter we will discuss the initialization of the members.
As already mentioned, if it is a domain, the compiler will initialize it by default, this section is no longer expanded, we need to pay attention to the local variables.
Local variables must be initialized, or the error will be directly.
The following is the wrong code:
Package Com.ray.ch01;public class Test {public static void main (string[] args) {int i;i++;}}
In i++ here the compiler will prompt for no initialization variables.
1. Specifying variable initialization
We give several methods for specifying initialization below.
(1) Direct initialization, assigning a value directly to the attribute domain
Package Com.ray.ch01;public class Test {private int id=0;}
(2) Return by method
Package Com.ray.ch01;public class Test {private int id = initid ();p rivate int Initid () {return 0;}}
Package Com.ray.ch01;public class Test {private int id = initid (0);p rivate 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 the book object is not created, it is used directly and throws an exception at run time.
(4) Pay attention to the order of execution and ensure that the member as a parameter has been initialized
The correct code:
Package Com.ray.ch01;public class Test {private int id = initid ();p rivate int Initid () {return 0;} private String name = Initname ("name-" +id);p rivate string Initname (string name) {return name;}}
The wrong code:
Package Com.ray.ch01;public class Test {private String name = Initname ("name-" +id);p rivate string Initname (string name) {R Eturn name;} private int id = initid ();p rivate int Initid () {return 0;}}
Two code exactly the same, just a change of location, in the wrong code, the ID is error, the ID is not initialized.
Summary: In this chapter we discuss the initialization of members, in particular the local variables and the initialization of several methods.
This chapter is here, thank you.
-----------------------------------
Directory
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Understanding the initialization of java-4.6 members from the beginning