Java in the order of initialization

xiaoxiao2021-03-05  20

When you create an object, all the data members of the object are first initialized, and if the member variables are object, they will also perform initialization in order. After all class members are initialized, the constructor in which the object is located is called to create an object. The function of constructing is initialization. Static objects (variables) initialize before non-static objects. Static objects (variables) are only initialized once, and the call is not initialized, but the non-static object is initialized every time the call is called. The static variables of the primary class in the program are initialized before the main () method is executed. Not only when the object is created, all static variables in the class should be initialized, and the static variables in the first access class (no objects are created), all static variables in this class should also be arranged in the class in the class. initialization. The order of initialization includes the order of constructing method calls as follows: 1. The static member of the primary class is first initialized. 2. The superclass of the primary class is called from the highest to the lowest order. 3. Nonstatic object (variable) of the primary class is initialized. 4. Call the constructor of the primary class. In one constructor, only other other construction methods can be called, and the statement that calls the constructor must be the first statement.

Class one {public one (string str) {system.out.println (str);}} class two {one one_1 = new one ("one-1"); one one_2 = new one ("one-2"); Static One One_3 = New One ("One-3"); Public Two (String Str) {system.out.println (Str);}} public class test {static two two_3 = new TWO ("Two-3"); Public static void main (string [] args) {system.out.println ("TEST Main () start ..."); TWO TWO_1 = New TWO ("Two-1"); system.out.println ("- ----------- "); TWO TWO_2 = New TWO (" Two-2 ");}}

One-3one-1One-2TWO-3TEST Main () Start ... One-1One-2TWO-1 ------------- One-1One-2TWO-2

转载请注明原文地址:https://www.9cbs.com/read-39082.html

New Post(0)