Welcome to Java Learning code and code block execution order

directory

  • Constructors in Java

    • Introduction to construction method

    • Constructor instance

      • Case 1

      • Case 2

  • Java several constructors in detail

    • Common construction method

    • Default constructor

    • Heavy-load construction method

    • The Java subclass constructor calls the superclass constructor

  • Introduction to code blocks in Java

  • Java code block usage

    • Local code block

    • Construct code block

    • Static code block

  • The execution order of Java code blocks, constructors (including inheritance relationships)

  • Refer to the article

Constructors in Java

Introduction to construction method

A constructor is a special method of a class that initializes a new object of the class. Every class in Java has a default constructor, which must have the same name as the class name and have no return type. The default return type of a constructor is the object type itself, and constructors cannot be modified by static, final, synchronized, abstract, and native.

Note: The constructor is used to initialize a new object, so the static modifier does not make sense; Constructors cannot be inherited by subclasses, so the final and abstract modifications are meaningless; Multiple threads do not simultaneously create the same object with the same memory address, so the synchronized modifier is unnecessary.

The syntax for the constructor is as follows:

Class class\_name {public class\_name(){} // Default no arguments constructor public ciass\_name(\[paramList]){} // Define constructor... // Class body}

In a class, methods with the same name as the class are constructors. Each class can have multiple constructors, but they are required to each contain different method parameters.

Constructor instance

Case 1

There are two main constructors: parameter-free constructors and parameter-filled constructors. Examples are as follows:

public class MyClass { private int m; // define the private variable MyClass() {// define the constructor m=0 without arguments; } MyCiass(int m) {this.m=m; }}

This example defines two constructors, a no-parameter constructor and a parameterized constructor. Method overloading is defining multiple methods of the same name with different parameters in a class. Both constructors have the same name as the class, MyClass. Different constructors can be called to initialize the class when it is instantiated.

Note: Class constructors are not required to be defined. If no constructor is defined in a class, Java automatically generates a default constructor for the class. The default constructor contains no arguments and the method body is empty. Java no longer provides a default constructor if one or more constructors are explicitly defined in a class.

Case 2

To create objects of a class with different initialization behaviors under different conditions, you need to create multiple constructors in a class. Here is an example to demonstrate the use of the constructor.

(1) First define two constructors in the employee class Worker, the code is as follows:

public class Worker { public String name; // private int age; Public Worker(String name) {this.name=name; } public Worker(String name,int age) {this.name=name; this.age=age; } public String toString() {return" hello! I am a new employee, my name is "+name+", this year "+age+". ; }}

Two attributes are defined in the Worker class, where the name attribute cannot be changed. Constructors with one and two parameters are defined and their properties initialized. Finally, we define the toString() method of the class, which returns an introduction statement for the new employee.

Tip: The Object class has a toString() method, which is a special method that every class created inherits and returns a String of type. If the method is defined in a class, the toString() method of the class is automatically called to return a string when the class object is called, and the contents of the returned string are printed out with system.out.println (object name).

(2) Create the main() method in the TestWorker class as the entrance of the program, invoke different constructors in the main() method to instantiate the Worker object, and initialize the attributes in the object, the code is as follows:

public class TestWorker { public static void main(String\[\] args) { System. Out. Println (" -- -- -- -- -- -- -- -- -- -- - with a parameter of the constructor -- -- -- -- -- -- -- -- -- -- - "); Worker worker1=new Worker(" zhang "); // Call the Staff constructor with one argument. System.out.println(worker1); System. The out. Println (" -- -- -- -- -- -- -- -- -- -- - a constructor with two arguments -- -- -- -- -- -- -- -- -- -- -- -- "); Worker worker2=new Worker(" li Li ",25); System.out.println(worker2); }}

In the above code, two different Worker objects are created: one is an employee object named Zhang Qiang, and the other is an employee object named Li Li and aged 25. For the first Worker object, Worker1, the age attribute value is not specified, so the program uses its default value of 0. For the second Worker object, Worker2, the name attribute value and age attribute value are specified respectively, so the program will reassign the passed parameter value to the attribute value in the Worker class.

Running the TestWorker class produces the following output:

----------- constructor with one argument ----------- Hello! I am a new employee. My name is Zhang Qiang and I am 0 years old. ----------- Constructor with two arguments ------------ Hello! I am a new employee. My name is Li Li and I am 25 years old.

By calling the constructor with parameters, the initialization of object members is completed when the object is created, which simplifies the code of object initialization.

Java several constructors in detail

Common construction method

The method name is the same as the class name

No return type

A subclass cannot inherit the constructor of its parent class

Static, final, and abstract cannot be modified by subclasses. Static, final, and abstract cannot be modified by subclasses. Abstract cannot be instantiated.

Can be private, can be instantiated within the class, but can not instantiate objects outside (note!!)

public class A{
    int i=0;
    public A(a){
        i=2;
    }
    public A(int i){
        this.i=i; }}Copy the code

Default constructor

If there are no constructors, a default constructor with no arguments is automatically added at compile time

Implicit default constructor

    public A(a){}
Copy the code

The default constructor displayed

    public A(a){
    System.out.print("Default constructor for display")}Copy the code

Heavy-load construction method

For example, the original class constructor has one parameter, and now the new object has three parameters, so we need to override the constructor

When there are multiple constructors in a class and repetitive operations are possible, you can use this to call other constructors.

public class A{
    private int age;
    private String name;
    public A(int age,String name){
        this.age=age;
        this.name=name;
    }
    public A(int age){
        this(age,Anonymous);// Call A(int age,String name) constructor
    }
    public A(a){
        this(1);// Call A(int age) constructor
    }
    public void setName(String name) {this.name=name; }public String getName(a) {returnname; }public void setAge(int age) {this.age=age; }public int getAge(a) {returnage; } } A a=new A(20."On Monday");
A b=new A(20);
A c=new A();
String name = a.getName();
String name1 = b.getName();
int age = c.getAge();
System.out.println(name);
System.out.println(name1);
System.out.println(age);
Copy the code

The Java subclass constructor calls the superclass constructor

First, superclass constructors are never inherited by subclasses.

The subclass constructor calls the constructor of the parent class. The point is that the subclass constructor calls the constructor of the parent class anyway.

The subclass constructor either calls the parent class constructor without arguments (including when the parent class has no constructor). The default no-argument constructor), or call the parent class with arguments. When the subclass constructor calls the parent class constructor with no arguments, it is usually not written by default. The default is super (), and it should be placed in the first line of the constructor. When a subclass constructor calls a constructor whose parent has arguments, the subclass constructor must call the superclass constructor with super (argument) in the first line of the constructor.

When the constructor of a subclass is a no-argument constructor, the parent class no-argument constructor must be called. Because the system will automatically look for the parent class to have a no-argument constructor, if not, the system will say that the parent class does not define a no-argument constructor.

When the subclass constructor is a parameter constructor, there are two situations. The first is that the subclass constructor does not say super, which means that you default to calling the parent class with no arguments constructor, just as if the subclass had no arguments constructor.

If the subclass constructor has a super (parameter), the system will find if the parent class has the same parameter constructor (parameter number, and type order must be the same). If the parent class does not have the same parameter constructor, it will also raise an error.

The same problem is encountered with overloading the this constructor. A single parameter constructor can call multiple parameter constructors.

Introduction to code blocks in Java

In Java, code blocks enclosed in {} are called code blocks. Code blocks can be classified into the following four types:

A brief introduction.

1. Common code block:

The body of a method in a class

2. Construct code block:

The constructor block is called when the object is created, every time it is created, and takes precedence over the class constructor.

Static code block:

Code snippets wrapped in static{} are executed only once. Static code blocks execute in preference to construction blocks.

4. Sync code blocks:

Using code blocks wrapped with synchronized () {}, in a multi-threaded environment, read and write operations on shared data need to be mutually exclusive; otherwise, data inconsistency will occur. Synchronized code blocks need to be written in methods.

Similarities and differences between static code blocks and constructed code blocks

Common: Each class is executed after the JVM loads the class and before the constructor executes. More than one class can be defined, and static variables are usually assigned in a code block.

Difference: Static code blocks are executed before non-static code blocks. A static block of code is executed only once on the first new and not after that. Instead of a static block executing every new time.

Java code block usage

Local code block

Location: local location (inside method)

Function: limit the life cycle of variables, release as soon as possible, save memory

Call: executed when the method it is in is called

 public classLocal code block{
@Test
public void test (a){
    B b = newB(); b.go(); }}class B {
    B(){}
    public void go(a) {
        // A partial block of code in a method, usually called once, is immediately freed to avoid occupying stack space during subsequent calls
        // Because stack space memory is limited, method calls may generate many local variables and run out of stack memory.
        // Use local code blocks to avoid this situation.
        {
            int i = 1;
            ArrayList<Integer> list = new ArrayList<>();
            while (i < 1000) {
                list.add(i ++);
            }
            for (Integer j : list) {
                System.out.println(j);
            }
            System.out.println("gogogo");
        }
        System.out.println("hello"); }}Copy the code

Construct code block

Location: The location of a class member, that is, outside of a method in the class

Purpose: To extract parts common to multiple constructors and share construction code blocks

Call: Each time the constructor is called, it takes precedence over the constructor execution, i.e., it is automatically called each time a new object is created, and the object is initialized

class A{
    int i = 1;
    int initValue;// Initialization of member variables is left to the code block
    {
        This is what a block of code does: it initializes a member variable with some code before calling the constructor.
        // instead of doing it at constructor time. Typically used to extract the same parts of a constructor.
        //
        for (int i = 0; i <100; i ++) { initValue += i; } } { System.out.println(initValue); System.out.println(i);// Prints 1
        int i = 2;// The variables in the code block do not conflict with the member variables, but the variables in the code block are used preferentially
        System.out.println(i);// Print 2
        //System.out.println(j); // Backreference is invalid 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);// Variables in a code block are automatically released after execution, without affecting code outside the code block
    }
    A(){
        System.out.println("Constructor run"); }}public classConstruct code block{
    @Test
    public void test(a) {
        A a = newA(); }}Copy the code

Static code block

Position: the position of the class member, usedstaticThe modified code block is used to perform some initialization on the class only once, whennewWhen there are multiple objects, a static code block is called only the first time, because static code blocks are classed and all objects share a call:newAutomatically called when an objectpublic classStatic code block{

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

The execution order of Java code blocks, constructors (including inheritance relationships)

This is a common interview question. To answer it, take a look at this example.

There are three classes: A, B, and C, where A is the parent of B, and C has no inheritance and only serves as the output

Class A:

public class A {

static {
    Log.i("HIDETAG"."A static code block");
}

private static C c = new C("A static member");
private  C c1 = new C(Members of the "A");

{
    Log.i("HIDETAG"."Block A");
}

static {
    Log.i("HIDETAG"."A static code block 2");
}

public A(a) {
    Log.i("HIDETAG"."A construction method"); }}Copy the code

Class B:

public class B extends A {

private static C c1 = new C("B static member");

{
    Log.i("HIDETAG"."B code block");
}

private C c = new C(Members of the "B");

static {
    Log.i("HIDETAG"."B Static code block 2");
}

static {
    Log.i("HIDETAG"."B static code block");
}

public B(a) {
    Log.i("HIDETAG"."B construction method"); }}Copy the code

Class C:

public class C {

public C(String str) {
    Log.i("HIDETAG", str + "Construction method"); }}Copy the code

Execute statement: new B();

The following output is displayed:

I/HIDETAG: A static code block I/HIDETAG: A static member constructor I/HIDETAG: A static code block2I/HIDETAG: B Static member constructor I/HIDETAG: B static code block2I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: A member constructor I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: B static code block I/HIDETAG: A member constructor I/HIDETAG: B Construction methodCopy the code

Conclusion:

The order of execution is: static member and code block subclass static member and code block superclass member initialization and code fast superclass constructor subclass member initialization and code block subclass constructorCopy the code

Note: You can see that the same level of code block and member initialization is performed from top to bottom in code order

After watching the above demo, let’s look at the following problem, see if you can handle it?

Look at the following code to find the order of execution:

class A {
    public A(a) {
        System.out.println("Constructor of class 1A");
    }
    {
        System.out.println("Class 2A construction is fast.");
    }
    static {
        System.out.println("Class 3A static block"); }}public class B extends A {
    public B(a) {
        System.out.println("Constructors of class 4B");
    }
    {
        System.out.println("Class 5B construction is fast.");
    }
    static {
        System.out.println("Static block of class 6B");
    }
    public static void main(String[] args) {
        System.out.println("Seven");
        new B();
        new B();
        System.out.println("8"); }}Copy the code

The execution sequence is 367215421548

Why is that?

Here are five things to know first:

Each time new executes the constructor as well as the building block. The contents of the constructor block are executed before the constructor method. Static blocks of non-main classes are executed once, before the constructor and the constructor block, when the class is loaded. Static blocks in the public class are executed before main. In inheritance, instantiation of a subclass executes the constructor of the parent class, produces the object of the parent class, and then calls the constructor of the subclass. So in the problem, since the main class B inherits from A, A will be loaded first, so the first execution is sentence 3.

From point 4 we know that 6 is executed before 7, so the first three sentences are 367.

B is instantiated twice. Each time, its parent class A is instantiated first, and then B is instantiated in the order 2154.

Then go to 8.

So the order is 367215421548

Refer to the article

Blog.csdn.net/likunkun\_\… www.jianshu.com/p/6877aae40… www.jianshu.com/p/49e45af28… Blog.csdn.net/du\_du1/art… C.biancheng.net/view/976.ht… Blog.csdn.net/evilcry2012… www.jb51.net/article/129…