java learning trap 02 Super, static variable, access modifier

1. Static variable

Static variables are shared by all objects in the class, and their values are modified when they are used.

usage method:

Class name. Variable name

Note: static methods can call static members of the same kind, not non static members and methods

Static initial block usage:

Static{

Only static variables can be initialized

};

The basic code block and code loading order of regular test interview static

brief introduction

This paper mainly introduces the characteristics and usage of three kinds of code blocks.

Code block: Code surrounded by {}

The code blocks in java are divided into four types according to their positions:
Local code block

Location: local location (inside method)
Function: limit the life cycle of variables, release as early as possible, and save memory
Call: executed when the method it is in is called

   

public class Local code block {
    @Test
    public void test (){
        B b = new B();
        b.go();
    }
    }
    class B {
        B(){}
        public void go() {
            //The local code block in the method is generally called once, and the space is released immediately after the call to avoid occupying the stack space in the next call process
            //Because the stack space memory is limited, method calls may generate many local variables, resulting in insufficient stack memory.
            //This can be avoided by using local code blocks.
            {
                int i = 1;
                ArrayList<Integer> list = new ArrayList<>();
                while (i < 10) {
                    list.add(i ++);
                }
                for (Integer j : list) {
                    System.out.println(j);
                }
                System.out.println("gogogo");
            }
            System.out.println("hello");
        }
    }

Output results:


Building blocks

Location: the location of a class member, which is outside the method in the class
Function: extract common parts of multiple construction methods and share construction code block
Call: every time the constructor is called, it will take precedence over the execution of the constructor, that is, it will be called automatically every time an object is new, initializing the object

The object is executed as soon as it is instantiated, once for each instantiation;

   

 class A{
        int i = 1;
        int initValue;//Initialization of member variables is done by code blocks
        {
            //The function of the code block is embodied in this: before calling the constructor, initialize the member variable with some code.
            //Instead of building a method call. It is generally used to extract the same part of the construction method.
            //
            for (int i = 0;i < 100;i ++) {
                initValue += i;
            }
        }
        {
            System.out.println(initValue);
            System.out.println(i);//Print 1
            int i = 2;//The variables in the code block do not conflict with the member variables, but the variables in the code block will be used first
            System.out.println(i);//Print 2 now
            //System.out.println(j); / / illegal backward reference is prompted, because the initialization of j has not started yet.
            //
        }
        {
            System.out.println("Code block run");
        }
        int j = 2;
        {
            System.out.println(j);
            System.out.println(i);//The variables in the code block will be released automatically after running, and the code outside the code block will not be affected
        }
        A(){
            System.out.println("Construction method run");
        }
    }
    public class Building blocks {
        @Test
        public void test() {
            A a = new A();
        }
    }

Execution result:


Static code block

Location: class member location, code block decorated with static

Function: to initialize a class and load it only once. When there are multiple new objects, only the static code block will be called for the first time. Because the static code block belongs to the class, all objects share one copy

Call: automatically call when new an object

   

public class Static code block {
     
    @Test
    public void test() {
        C c1 = new C();
        C c2 = new C();
        //As a result, a static block is called only once, and all objects of the class share the block
        //Generally used for class global information initialization
        //Static code block call
        //Code block call
        //Construct method call
        //Code block call
        //Construct method call
    }
     
    }
    class C{
        C(){
            System.out.println("Construct method call");
        }
        {
            System.out.println("Code block call");
        }
        static {
            System.out.println("Static code block call");
        }
    }

Call result:

Execution order static code block construction code block construction method
Written examination questions

Actual interview questions:

Write the output of the following program:

    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();
        }
    }

Execution result:

Analysis: first of all, we need to know that static code blocks are loaded with the class, while construction code blocks and construction methods are loaded with the object creation

1. When compiling HelloB.java, because HelloB inherits HelloA and loads HelloA class first, the static code block of HelloA class executes first, then the static code block of HelloB class and HelloB class executes. That's nothing to say

2. Then create the Object of HelloB. We all know that the construction code block takes precedence over the execution of the construction method. At this time, we should first look at the construction method of HelloB class. In the construction method of HelloB class, there is an implicit super () that is executed first, so find the construction method of HelloA class, In the construction method of HelloA class, there is also an implicit super() execution (calling the construction method of Object class), which does not return any results. Next, I'm a class of HelloA class is executed before the method body of HelloA class is executed, then the method body of HelloA class is executed (that is, Hello A), and finally the construction method of HelloB class is executed, At this time, the super() of HelloB class has been executed. Before executing the method body of HelloB class, execute the I'm B class of HelloB class, and then execute the method body of Zi class

No inheritance initialization order:

Inherited initialization order:

Let's take a look at Ali's written test:

  

  public class B
    {
        public static B t1 = new B();
        public static B t2 = new B();
        {
            System.out.println("Tectonic block");
     
        }
        static
        {
            System.out.println("Static block");
     
        }
     
        public static void main(String[] args)
        {
     
            B t =new B();
     
        }
    }

The execution result is:

Why not:

Static block

Tectonic block

Tectonic block

Tectonic block

As a result of:

Static block: it is declared statically and executed only once when the JVM loads the class

Building block: directly defined in the class with {} and executed every time an object is created

Execution order priority: static block > main () > building block > construction method

Because of the static declaration, T1 and T2 also rise to the static bit. They are at the same priority as the static block. For the same priority, the objects, construction objects and static blocks are constructed in order
--------
Copyright notice: This is the original article of CSDN blogger "Harry ptter", following CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/harrypter/article/details/87875399

 

Published 2 original articles, praised 0 and visited 21
Private letter follow

Keywords: Java jvm

Added by wempy on Sun, 08 Mar 2020 15:26:29 +0200