java interview often test code is loaded and the code block based sequential static

Transfer:   https://blog.csdn.net/harryptter/article/details/87875399

 

 https://blog.csdn.net/harryptter/article/details/87875399
in the interview large companies, if you encounter a large state-owned enterprises or large private Internet, written in pen questions frequently encountered code blocks and code loading sequence. Here to do a summary, but also the convenience of our small partners do not motion sickness.

Source github address: https: //github.com/harrypitter/JavaBase.git

Part Reprinted from: https: //blog.csdn.net/a724888/article/details/80069472

table of Contents

Brief introduction

Partial block

Configuration code block

Static code block

Pen questions

Introduction
This paper describes the features and uses three kinds of code blocks.

Block of code: Code surrounded by {}

java its position in the code block is divided into four:

Partial block
position: position of a local (internal method)
effect: the life cycle defined variables, the early release, to save memory
executed when its method invocation: Call

public class partial block {
@Test
public void Test () {
    B B B = new new ();
    b.go ();
}
}
class B {
    B () {}
    public void Go () {
        // local process code block, usually a one-time call, call the immediate release of finished space, to avoid the occupation stack space during the next call
        // because the stack memory space is limited, method calls might generate a lot of local variables lead to insufficient stack memory .
        // local use code blocks to avoid such a situation occurs.
        {
            Int I =. 1;
            the ArrayList <Integer> = new new List the ArrayList <> ();
            the while (I <10) {
                List.add (I ++);
            }
            for (Integer J: List) {
                System.out.println ( J);
            }
            System.out.println ( "GOGOGO");
        }
        System.out.println ( "Hello");
    }
}
The output:


Configuration code block
location: class member position is a position outside of class methods
action: the portions common to the plurality of extracted configuration method, the common code block configured
to call: Each constructor method is called in the constructor will be preferentially executed , which is automatically invoked every time a new object is initialized object

An example of the implementation of objects, each instantiated once executed once;

A {class
    int I =. 1;
    int initValue; // initialize member variables to the complete block of code
    {
        // code block role reflected thereto: Before calling the constructor, by a piece of code to the member variables are initialized.
        // instead then when the constructor is called. It is typically used to extract the same portion of the constructor.
        //
        for (int I = 0; I <100; I ++) {
            initValue + = I;
        }
    }
    {
        System.out.println (initValue);
        System.out.println (I); // this time printed . 1
        int I = 2; // variables in the block and member variables without conflicts, but using the variable priority code block
        System.out.println (i); // a print 2
        //System.out.println ( j); // prompt illegal back-reference, because the initialization of j has not yet begun.
        //
    }
    {
        System.out.println ( "Code Block Run");
    }
    J = 2 int;
    {
        System.out.println (J);
        System.out.println (I); // automatically released after code block variable and do not affect the code other than the code block
    }
    A () {
        System.out.println ( "run constructor");
    }
}
public class configuration block {
    @Test
    public void Test () {
        A = A new new A ();
    }
}
 The results:


A static block
 location: class member position, by a modified static block

 Role: class load some initialization only once, when a new multiple objects, only the first static code block calls, because the static code block belongs to the class, all objects share a

 Call: automatically called when a new object is 

public class static code blocks {
 
@Test
public void Test () {
    C = C1 new new C ();
    C C2 = C new new ();
    all objects // result, static block of code called once only, share the class code block
    // initialize the global information for the general class
    // static code block calls
    // calls the code block
    // constructor method call
    // calls the code block
    // constructor calls
}
 
}
class C {
    C () {
        System.out.println ( "constructor calls");
    }
    {
        System.out.println ( "Code block calls");
    }
    static {
        System.out.println ( "static code block calls");
    }
}
call results:


 

Static code block execution order -> block configured ---> Constructor

Pen questions
the actual interview questions:

Write the following program output:

public class HelloA {
    public HelloA(){
        System.out.println("HelloA");
    }
    {
        System.out.println("I'm A class");
    }
 
    static {
        System.out.println("static A");
    }
}
 
public class HelloB extends HelloA {
    public HelloB(){
        System.out.println("HelloB");
    }
    {
        System.out.println("I'm B class");
    }
 
    static {
        System.out.println("static B");
    }
 
    public static void main(String[] args) {
        new HelloB();The results:}
    }

 

Analysis: The first thing to know the static code block is loaded with class and load, constructed block and construction methods are being loaded with the creation of objects

1, when compiling HelloB.java, due HelloB inheritance HelloA, to load the HelloA classes, HelloA kind of static code block is executed first, and then load HelloB class, HelloB class static block of code execution, which have nothing to say

2, and then create HelloB object, we all know that construction code block execution in preference to the constructor, this time the question is, then should look at the class constructor HelloB, HelloB class constructor method, there are an implicit super () is executed first, so finding HelloA class constructor, and the constructor HelloA class also has an implicit super () (constructor calls the Object class) execution, and no result is returned, the next is in method HelloA class constructor is executed before execution of the configuration of the precursor block HelloA class (I'm a class), then perform a method thereof HelloA class constructor (i.e. Hello a), and finally back to the class structure HelloB methods, the time HelloB class super () has finished execution, configured to execute the code block HelloB class constructor is executed before the method body HelloB class (I'm B class), then class constructor is executed Zi body (HellB).

No inheritance initialization sequence:

Inheritance initialization sequence:

 Next, look at a pen Ali questions:

B class public
{
    public static new new B = B T1 ();
    public static new new B = B T2 ();
    {
        System.out.println ( "building block");
 
    }
    static
    {
        System.out.println ( "static block" );
 
    }
 
    public static void main (String [] args)
    {
 
        B T new new B = ();
 
    }
}
execution result is:

Why not:

Static block

Building blocks

Building blocks

Building blocks

 

The reason is that:

Static block: perform the JVM load the class with a static affirmed executed only once

Building blocks: perform a class defined by {}, each created object directly

The priority order of execution: Static blocks> main ()> building block> Constructor

Because static statement sake T1, T2 rises to a static position, with the static blocks are in the same priority, it is first to take the same priority order to construct an object, the object is constructed, the static block

 

 

 

 

 


 
--------------------- 
Author: harryptter 
Source: CSDN 
Original: https: //blog.csdn.net/harryptter/article/details/87875399 
Disclaimer: This article as a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin blog.csdn.net/qq_36688928/article/details/91418903