SoFunction
Updated on 2025-05-09

Detailed explanation of the usage of Java basic constructors, code blocks, and class loading timing

1. Constructor details

A class can define multiple different constructors, i.e.Constructor reload

  • For example: we can define a constructor for the Person class. When creating an object, we only specify the name of the person without specifying the age.
  • The constructor name and class name must be the same;
  • The constructor has no return value;
  • The constructor isComplete the initialization of the object, not creating an object;
  • existWhen creating an object, the system automatically calls the constructor of this class;
  • If the programmer does not define a constructor, the system will automatically generate a classDefault parameterless constructor(also called the default constructor), for exampleDog (){}
  • Once you have defined your own constructor,The default constructor is overridden, the default parameterless constructor cannot be used unless explicitly defined, i.e.:Dog0){}

2. Code block details

2.1 Code Block

Coded blocks are also calledInitialize block, a member of the class [that is, a part of the class], is similar to a method, encapsulating logical statements in the method body and enclosing them.

But unlike a method, there is no method name, no return, no parameters, only the method body, and there is no need to be explicitly called through objects or classes, butImplicitly called when loading a class, or when creating an object

grammar:

[Modifier]{
	//Code	}

Note:

1)ModifierOptional, if you want to write, you can only writestatic

2) Code blocks are divided into two categories, usingstaticThe modified one is calledStatic code blocks,NostaticModified, calledNormal code block/non-static code block

3) Logical statements can be any logical statement (input, output, method call, loop, judgment, etc.);

4) At the end of the code block;The number can be written or omitted.

Understanding: Code blocks can be initialized relative to another form of constructor (a supplementary mechanism for constructors).

Scenario: If there are repeated statements in multiple constructors, they can be extracted into code blocks to improve the reusability of the code.

Case:

public class CodeBlock01 {
    public static void main(String[] args) {

        Movie movie = new Movie("Hello, Lee Huanying");
        ("===============");
        Movie movie2 = new Movie("Detective Chinatown 3", 100, "Chen Sicheng");
    }
}

class Movie {
    private String name;
    private double price;
    private String director;

    //3 constructors-》Reload    //Interpretation    //(1) The following three constructors have the same statement    //(2) This way the code looks redundant    //(3) At this time, we can put the same statement into a code block,    //(4) In this way, no matter which constructor we call and create an object, we will first call the content of the code block.    //(5) The order of code block calls takes precedence over the constructor..    
    {
        ("Movie screen open...");
        ("The ad starts...");
        ("The movie is just the beginning...");
    };

    public Movie(String name) {
        ("Movie(String name) Being called...");
         = name;
    }

    public Movie(String name, double price) {
         = name;
         = price;
    }

    public Movie(String name, double price, String director) {
        ("Movie(String name, double price, String director) Being called...");
         = name;
         = price;
         = director;
    }
}

2.2 Static code blocks & class loading timing ⭐⭐⭐

Detail 1

1)⭐staticCode blocks are also called static code blocks. They are used to initialize the class, and they are executed as the class is loaded and will only be executed once. If it is a normal code block, every time an object is created, it will be executed.

Detail 2

2) When will the ⭐class be loaded

  • When creating an object instance (new);
  • Create a subclass object instance and the parent class will also be loaded;
  • When using static members of a class (static properties, static methods);

Case 1:

//1. When creating an object instance (new)AA aa = new AA();

class AA {
    // Static code block    static {
        ("AA's static code 1 is executed...");
    }
}

AA's static code 1 is executed...

Case 2:

//2. Create a subclass object instance, and the parent class will also be loaded. Moreover, the parent class will be loaded first, and the child class will be loaded later.AA aa2 = new AA();

class BB {
    // Static code block    static {
        ("BB's static code 1 is executed...");//1
    }
}
class AA extends BB {
    // Static code block    static {
        ("AA's static code 1 is executed...");//2
    }
}

BB's static code 1 is executed...
AA's static code 1 is executed...

Case 3:

//3. When using static members of a class (static properties, static methods)(Cat.n1);
 
class Animal {
    // Static code block    static {
        ("Animal's static code 1 is executed...");//1
    }
}
class Cat extends Animal {
    public static int n1 = 999;//Static properties 3    // Static code block    static {
        ("Cat's static code 1 is executed...");//2
    }
}

Animal's static code 1 is executed...
Cat's static code 1 is executed...
999

Detail 3

3) Ordinary code blocks will be called implicitly when creating an object instance. Once created, they will be called once.

ifJust useWhen a static member of the class,Normal code blocks will not be executed

summary:

  • 1. When the static code block is a class loading, it will be executed only once;
  • 2. Ordinary code blocks are called when creating objects, created once, and called once.

Detail 4

4) When creating an object, in the order of a class call: ⭐⭐

  • Call static code blocks and static attribute initialization (note: static code blocks and static attribute initialization calls have the same priority. If there are multiple static code blocks and multiple static variables initialization, they will be called in the order they define);
  • Call the initialization of ordinary code blocks and ordinary attributes (note: the priority of ordinary code blocks and ordinary attribute initialization calls is the same. If there are multiple ordinary code blocks and multiple ordinary attribute initializations, they will be called in the order of definition);
  • Call the constructor (i.e., the constructor).

Typical cases:

A a = new A();

class A {
    { //Normal code block        ("A Normal Code Block 01");
    }
    private int n2 = getN2();//Initialization of normal attributes
    static { // Static code block        ("A Static Code Block 01");
    }

    //Initialization of static properties    private static  int n1 = getN1();

    public static int getN1() {
        ("getN1 is called...");
        return 100;
    }
    public int getN2() { //Normal method/Non-static method        ("getN2 is called...");
        return 200;
    }

    //No parameter constructor    public A() {
        ("A() The constructor is called");
    }
}

A Static code block 01
getN1 is called...
A Normal code block 01
getN2 is called...
The A() constructor is called

Details 5

5) The front of the constructor actually impliessuper()and call normal code blocks,Static related code blocks, attribute initialization, and execution is completed when the class is loaded., therefore takes precedence over constructor and ordinary code block execution.

Case:

new BBB();

class AAA { //Premium class Object    {
        ("AAA's normal code block");
    }
    public AAA() {
        //(1)super()
        //(2) Calling the normal code block of this class        ("AAA() The constructor is called....");
    }
}
class BBB extends AAA  {
    {
        ("BBB's normal code block...");
    }
    public BBB() {
        //(1)super()
        //(2) Calling the normal code block of this class        ("BBB() The constructor is called....");
    }
}

AAA's normal code blocks
The AAA() constructor is called...
BBB's normal code block...
The BBB() constructor is called...

Details 6

6) When creating a subclass object with an inheritance relationship, theirStatic code block, static attribute initialization, ordinary code block, ordinary attribute initialization, construction methodThe order of call is as follows: ⭐⭐⭐

  • Static code blocks and static properties of the parent class (the priority is the same, executed in the order of definition);
  • Static code blocks and static properties of subclasses (the priority is the same, executed in the order of definition);
  • The normal code block of the parent class is initialized with normal attributes (the priority is the same, executed in the order of definition);
  • The constructor of the parent class (constructor);
  • The normal code block of the subclass is initialized with normal attributes (the priority is the same, executed in the order of definition;
  • The constructor of the subclass (constructor).

Classic Case:

new B02();

class A02 { //Premium class    private static int n1 = getVal01();
    static {
        ("A static code block for A02...");//(2)
    }
    {
        ("The first normal code block of A02...");//(5)
    }
    public int n3 = getVal02();//Initialization of normal attributes    public static int getVal01() {
        ("getVal01");//(1)
        return 10;
    }

    public int getVal02() {
        ("getVal02");//(6)
        return 10;
    }

    public A02() {//Constructor        //hide        //super()
        //Initialization of normal code and normal attributes...        ("Constructor of A02");//(7)
    }

}
class B02 extends A02 { //

    private static int n3 = getVal03();

    static {
        ("A static code block for B02...");//(4)
    }
    public int n5 = getVal04();
    {
        ("The first normal code block of B02...");//(9)
    }

    public static int getVal03() {
        ("getVal03");//(3)
        return 10;
    }

    public int getVal04() {
        ("getVal04");//(8)
        return 10;
    }
    //Be sure to taste it slowly...    public B02() {//Constructor        //Hidden        //super()
        //Initialization of ordinary code blocks and ordinary properties...        ("Constructor of B02");//(10)
    }
}

Details 7

7) Static code blocks can only directly call static members (static properties and static methods), and ordinary code blocks can call any members.

Classic Case:

class C02 {
    private int n1 = 100;
    private static int n2 = 200;

    private void m1() {}
    
    private static void m2() {}

    static {
        // Static code blocks can only call static members        //(n1); Error        (n2);//ok
        //m1();//Error        m2();
    }
    {
        //Ordinary code block, any member can be used        (n1);
        (n2);//ok
        m1();
        m2();
    }
}

200
100
200

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.