Initialization of Java object-related elements

Source: Internet
Author: User

1. Initialization of member variables, constructors, and member methods of a class

When a class uses the New keyword to create an object, such as person per = new person (); The JVM looks for a matching class based on person (), and then finds the class-matching construction method, which is a parameterless construct, and if no constructor is given in the program, the JVM defaults to a parameterless construct. When you create an object, you must call the constructor of the class to initialize the object's data. The JVM allocates memory space to this object, that is, allocates memory space to the member variables of the class, and if the class is assigned a value in the definition of the member variable, it is evaluated by the initial value, and the JVM will automatically initialize the value according to the rule if it is declared without assigning an initial value. The member method is loaded into the stack memory from the method area when the object calls this method, freeing the memory space immediately after it is exhausted.

Initialization process: Member variable, constructor--member method.

 PackageCom.yyq;/*** Created by Administrator on 2015-10-30.*/classPerson {intAge ;    String name;  PublicPerson () {System.out.println ("This was person ()"); System.out.println ("Name:" + This. Name + "; Age: "+ This. Age); }     Public voidShow () {System.out.println ("This is show ()"); System.out.println ("Name:" + This. Name + "; Age: "+ This. Age); }} Public classEXERCISE01 { Public Static voidMain (string[] args) {person per=NewPerson ();        Per.show (); Per.age= 30; Per.name= "Wendy";    Per.show (); }}
Output Result:This was person () Name:null; Age:0this is show () Name:null; Age:0this is show () Name:wendy; Age:30

2. Class member variables, static code blocks, construction code blocks, local code blocks, construction methods, member methods initialization process

Static code blocks appear in the class outside of the method's member position, with static modifiers, and are typically used to initialize the class. static code blocks are executed when the class is first invoked or instantiated. Static code blocks are executed only once, and are typically used to initialize some values and are shared globally across all objects. Constructing code blocks appears in the class outside of the method's member position, you can put together code that is common in multiple construction methods, each call construct executes, and executes before the method is constructed, initializing the object. Local code blocks appear in methods, local locations, limit the life cycle of variables, release early, and improve memory utilization.

initialization procedure: a static block of code (only once) constructs a code block, which is executed each time the constructor method is called. The execution order is independent of the exact location of the code block.

The order in which the local code blocks are initialized is determined by the specific location.

 PackageCom.yyq;/*** Created by on 2015-10-30.*/classCodeblockdemo {//Static code block    Static {        intA = 1000; System.out.println ("Static code Block 1:" +a); }    //Building Code Blocks    {        intx = 100; System.out.println ("Construct code block 1:" +x); }    //Construction Method     PublicCodeblockdemo () {System.out.println ("Exercise02 ()"); }    //Construction Method     PublicCodeblockdemo (inta) {System.out.println ("Exercise02 (int a):" +a); }    //Building Code Blocks    {        inty = 200; System.out.println ("Construct code block 2:" +y); }    //Static code block    Static {        intb = 2000; System.out.println ("Static code block 2:" +b); }} Public classexercise02{ Public Static voidMain (string[] args) {//Local code block        {            intx = 10; System.out.println ("Local code Block 1:" +x); }        //error: Symbol not found//System.out.println (x);System.out.println ("Demo One---------------"); Codeblockdemo Ex1=NewCodeblockdemo (); System.out.println ("Demo Two---------------"); Codeblockdemo EX2=NewCodeblockdemo (); System.out.println ("Demo Three---------------"); Codeblockdemo ex3=NewCodeblockdemo (1); {            inty = 20; System.out.println ("Local code block 2:" +y); }    }}
Output Result:Local code block 1:10 demonstrates a---------------static code block 1:1000 ==> static code block is only called when the class first creates the object, and the initialization order is independent of the location of the code static code block 2:2000 constructs a code block 1:100 = = = Constructs a block of code that is called every time the object is initialized, and the initialization order is not related to where the code is located constructs a block of code 2:200EXERCISE02 () demonstrates two---------------constructs a code block 1:100 ==> The construction code block is called every time the object is initialized, and the initialization order is independent of the location of the code constructs a code block 2:200EXERCISE02 () demonstrates three---------------constructs a code block 1:100 ==> The construction code block is called every time the object is initialized, and the initialization order is independent of the location of the code block 2:200EXERCISE02 (int a): 1 local code block 2:20 ==> The local code block is simply the sequential execution of the program, related to the actual location

The member variable and member method are not included in the analysis, but we can know that the static code block is initialized when the class is loaded, and the member variable is to allocate memory according to the construction method when the object is created, initialize the assignment, So if you print a member variable or a member variable assignment in a static code block, an error appears, showing that you want to change the variable type to static, and that it works correctly in both the construction block and the constructor method.

Initialization procedure: a static block of code (one time only), a member variable (each time the object is created with an initialization assignment), constructs a code block (each call to the construction method), and constructs a method (each time the object is created will call a matching constructor) Member methods (run when the object is called).

3. Initialization of member variables, constructor methods, member methods for parent and child classes that have inheritance relationships

When the subclass object is created, it calls the constructor of the subclass, in fact the first execution statement of the subclass's constructor is super (), which automatically calls the parent class's parameterless construction method, which means it automatically detects the parent class inherited by the subclass and initializes the member variables of the parent class. When you have initialized the member variables of the parent class, the constructor method, the member variables and the constructor methods of the child class are initialized. Because subclasses inherit non-private member variables and member methods of the parent class (where I define the member variables and member methods as default access permissions), the subclass defines the same member variable, which is overwritten at initialization time, and the member method executes the parent class if the parent class has no child class at the time of the call. If the parent class does not have a subclass of methods to execute subclasses, and if the parent class has subclasses, then the member method of the subclass is the member method of the parent class, and the final execution is the member method of the child class.

Initialization procedure: Parent class, member variable, parent constructor method, child class member variable--subclass constructor Method--parent class/Subclass member method.

 PackageCom.yyq;/*** Created by Administrator on 2015-10-30.*/classfather{intAge = 40; String name= "Father"; intnum = 321;  PublicFather () {System.out.println ("Father ()"); System.out.println ("Name:" +name+ "; Age: "+age+"; Num: "+num); }     Public voidShow () {System.out.println ("I am Father."); }     Public voidPlay () {System.out.println ("Father play."); }};classSonextendsfather{intAge = 15; String name= "Son";  PublicSon () {System.out.println ("Son ()"); System.out.println ("Name:" +name+ "; Age: "+age+"; Num: "+num); }     Public voidShow () {System.out.println ("I am Son."); }     Public voidStudy () {SYSTEM.OUT.PRINTLN ("Son play."); }} Public classExercise03 { Public Static voidMain (string[] args) {son son=NewSon ();        Son.show ();        Son.play ();    Son.study (); }}

Output Result:

Father ()

Name:father; age:40; num:321

Son ()

Name:son; age:15; num:321

I am Son.

Father play.

Son play.

4. member variables, static code blocks, construction code blocks, constructor methods, member methods of parent and child classes that have inheritance relationships

Because if there is a subclass of the inheritance relationship and the parent class, the child class object is created automatically when the parent class's constructor is called, and the data of the parent class is initialized. But if both the parent class and the subclass have static blocks of code, then the static code blocks of the parent class are executed first, and then the static blocks of the subclasses are executed, because the static code block does not need to create the object to execute, so the static code block is run first when the class is loaded, and then the constructor of the parent class is run. Finally, the construction of code blocks and subclasses that run subclasses is constructed.

Initialization process: Parent class static code block, subclass static code block, parent class construction code block, parent class construction method, subclass construct code block, subclass construction method

 PackageCom.yyq;/*** Created by Administrator on 2015-10-30.*/classbaseclass{Static{System.out.println ("Static code block BaseClass"); } {System.out.println ("Building code block BaseClass"); }     PublicBaseClass () {System.out.println ("Construction Method BaseClass"); }}classSonclassextendsBaseClass {Static{System.out.println ("Static code block Sonclass"); } {System.out.println ("Building code block Sonclass"); }     PublicSonclass () {System.out.println ("Construction Method Sonclass"); }} Public classEXERCISE04 { Public Static voidMain (string[] args) {Sonclass son1=NewSonclass (); System.out.println ("-------------------"); Sonclass Son2=NewSonclass (); }}

Output Result:Static code block baseclass static code block sonclass construct code block BaseClass construct method baseclass construct code block Sonclass construct method Sonclass-------------------construct code block BaseClass construction Method basec Lass Constructing code block Sonclass construction Method Sonclass

Initialization of Java object-related elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.