Java Learning _ Interesting code snippets (i)

Source: Internet
Author: User

Keep an interesting code snippet in mind

Yesterday saw a very interesting question, then I saw the problem of the moment I was ignorant. In fact, their own knowledge is not solid. Now I separate it by the line of analysis, if wrong, please correct me! The main is not a solid understanding of the basic knowledge, the future will encounter a lot of problems, just a Java learning Interesting Code snippets (a).

The first one.

The code is as follows

 PackageCOM.ZHB; Public  class Test {    StaticTest test =NewTest ("3");Static{System.out.println ("1"); } {System.out.println ("2");    } Test (String s) {System.out.println (s); } Public Static void staticfunction() {System.out.println ("4"); } Public Static void Main(string[] args)    {staticfunction (); }}

See this code, I thought I just summed up the static code block summary, this is a cinch! The result should be 1 2 3 4.
After running, I found out what a ghost!
* Correct running Result: 2 3 1 4 *

Disassembly analysis 1. First, let's review the knowledge of the code block.
 PackageCOM.ZHB; Public  class Demo1 {    /** * Static code block * /    Static{System.out.println ("Static code block"); }/** * Construction Code * /{System.out.println ("Building Code blocks"); }/** * No parameter constructor */     Public Demo1() {System.out.println ("no parameter constructor"); }/** * Constructor with parameters * /     Public Demo1(intnum) {System.out.println ("constructor with parameters"); } Public Static void Main(string[] args) {System.out.println ("==================");NewDemo1 (); System.out.println ("==================");NewDemo1 (2); }}

Execution results
Static code block

==================
Building code Blocks
No parameter constructor

==================
Building code Blocks
Constructors with parameters

From which we can see

    • Static code block It is executed as the class loads, as long as the class is loaded, and is loaded only once, primarily for initializing classes;
    • New an object always executes the construction code first, while executing the constructor, but one thing to note is that the construction code is not run before the constructor, it is performed by the constructor.

    • Constructing a code block executes once for each object that is created. The constructor is initialized for a particular object, and the construction code is initialized for all objects, with different scopes.

    • Execution order: Static code block > construct code block > constructor

2, reproduce the structure code in the original problem
 PackageCOM.ZHB; Public  class Demo2 {    StaticDemo1 Demo1 =NewDemo1 ();/** * Static Construction code */    Static{System.out.println ("Demo2 Static construction code block"); }/** * Construction Code * /{System.out.println ("Demo2 Construction code block"); }/** * No parameter constructor */     Public Demo2() {System.out.println ("Demo2 Non-parametric constructor"); }/** * Constructor with parameters * /     Public Demo2(intnum) {System.out.println ("Demo2 constructor with parameters"); } Public Static void Main(string[] args) {System.out.println ("==================");NewDemo2 (); System.out.println ("==================");NewDemo2 (2); }}

Execution Result:
Static code block
Building code Blocks
No parameter constructor
Demo2 statically constructed code blocks

==================
Demo2 Constructing code blocks
Demo2 Non-parametric constructors

==================
Demo2 Constructing code blocks
Demo2 Constructors with parameters

from which we know

    • Static variables and statically constructed blocks of code are peers;
    • Static executes in order
Further walkthroughs
 PackageCOM.ZHB; Public  class Demo2 {    //static Demo1 demo1 =new Demo1 ();    StaticDemo2 Demo2 =NewDemo2 ();/** * Static Construction code */    Static{System.out.println ("Demo2 Static construction code block"); }/** * Construction Code * /{System.out.println ("Demo2 Construction code block"); }/** * No parameter constructor */     Public Demo2() {System.out.println ("Demo2 Non-parametric constructor"); }/** * Constructor with parameters * /     Public Demo2(intnum) {System.out.println ("Demo2 constructor with parameters"); } Public Static void Main(string[] args) {System.out.println ("==================");NewDemo2 (); System.out.println ("==================");NewDemo2 (2); }}

The code structure at this point is the same as the original question.

    • Execute the static part sequentially, first execute the static Demo2 Demo2 =new Demo2 ();

    • At this point, the construction code is always executed first when you new an object.
      Execute System.out.println ("Demo2 Construction Code block");

    • Executes the constructor System.out.println ("Demo2 parameterless constructor"), at which point the Demo2 ends

    • Sequential execution of statically constructed code

    • Subsequent normal execution (explained earlier)

Execution Result:
Demo2 Constructing code blocks
Demo2 Non-parametric constructors
Demo2 statically constructed code blocks

==================
Demo2 Constructing code blocks
Demo2 Non-parametric constructors

==================
Demo2 Constructing code blocks
Demo2 Constructors with parameters

At this point, I understand why the original program was such a result.

A second question

We have changed the procedure of the original question to the following

package com.zhb;publicclass Test {    staticnew Test();    new Test();    publicstaticvoidmain(String[] args) {    }}

Error after execution

    • Exception in thread "main" Java.lang.StackOverflowError *

Why is this question?

Quiet analysis of the next

1. We know to run static first.
2.static test test = new test (); Initializes the test class, instantiating the member variables of the class
3. Instantiate the Test2, but Test test2 = new test (), and then instantiate the Test2 and loop all the time
4. Cause Stack Overflow

Here's another question: the process of initializing an instance variable of a class

class B {  privateint10;  publicB(){    100;  }}

After compiling into a class file, use the command javap-c B.class to decompile

//Part One: Parent class <init> () method0: Aload_01: Invokespecial #1                  //Method java/lang/object. " <init> ":() V///Part Two: instance variable initialization, which is the assignment when defining a variable4: Aload_05: BipushTen7: Putfield #2                  //Field b:i//Part III: Constructor method bodyTen: Aload_0 One: Bipush - -: Putfield #2                  //Field b:i -:return

Learn here to summarize what you have learned before:
* The sequence of Java instance variables at initialization is the constructor code block, which is directly assigned to the initialization code (XXX->XXX->XXX) of the parent class, as defined by the variable. *

Because I am also a rookie, a lot of smattering, if wrong, please correct me.

Reference:

1.http://blog.csdn.net/chenssy/article/details/14486833
2.http://blog.csdn.net/cauchyweierstrass/article/details/48943077

Java Learning _ Interesting code snippets (i)

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.