Chapter 15 Java se special topic object-oriented advanced II - code block details

1. Code block overview

  • Code block: also known as initialization block, it is a member of a class, similar to a method. It encapsulates logical statements in the method body and is surrounded by {};
  • And methods:
    • 1. No method name, no return value, no parameter, only method body;
    • 2. It is not called explicitly through an object or class, but implicitly when loading a class or creating an object
  • Basic grammar
[Modifier ] {
    code
}
  • matters needing attention:

    • 1. Modifier is optional. If you want to write, you can only write static;
    • 2. There are two types of code blocks. Static code blocks are those modified by static, while ordinary code blocks are those without static;
    • 3. Logical statements can be arbitrary logical statements (input, output, method call, loop, judgment, etc.);
    • 4,; The number can be written or omitted;
  • example

/*
1,The following three constructors have the same statement;
2,It seems that the code is a little 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 to create an object, we will call the content of the code block first;
5,The calling order of code blocks takes precedence over constructors
*/

//1. Create Child class
public class Child {

    {
        System.out.println("Code block advertising!!!");
    }

    private String school;
    private String name;
    private double age;

    public Child(String name){
        System.out.println("One parameter advertising!!!");
        this.name = name;
    }

    public Child(String school, String name) {
        System.out.println("Two parameters advertising!!!");
        this.school = school;
        this.name = name;
    }

    public Child(String school, String name, double age) {
        System.out.println("Three parameters advertising!!!");
        this.school = school;
        this.name = name;
        this.age = age;
    }

    public void join(){
        System.out.println(name + "Joined the game...");
    }
}

//2. Create the main method and call the Child class
public class main {
    public static void main(String[] args) {
        Child child1 = new Child("li");

        Child child2 = new Child("li","primary school");
        
        Child child3 = new Child("li","zhi",112);
    }
}
  • Operation results

  • Benefits of code blocks

    • 1. Equivalent to another form of constructor, which can do initialization operation;
    • 2. If multiple constructors have the same repeated statements, they can be extracted into the code block to improve the reusability of the code;

2. The difference between static code block and ordinary code block

Code block categoryDefinition methodDetailed overview
Static code blockCode block modified by staticThe class is initialized and executed as the class is loaded, and only once
Common code blockCode block not modified by staticCreate an object and execute it
  • example
//1. Create Child class
public class Child {

    static {
        System.out.println("Advertising!!!");
    }
    
    private String school;
    private String name;
    private double age;

    public Child(String name){
        System.out.println("Advertising!!!");
        this.name = name;
    }

    public Child(String school, String name) {
        System.out.println("Advertising!!!");
        this.school = school;
        this.name = name;
    }

    public Child(String school, String name, double age) {
        System.out.println("Advertising!!!");
        this.school = school;
        this.name = name;
        this.age = age;
    }

    public void join(){
        System.out.println(name + "Joined the game...");
    }
}


//2. Create the main method and call the Child class
public class main {
    public static void main(String[] args) {
        Child child1 = new Child("li");

        Child child2 = new Child("li","primary school");
        
        Child child3 = new Child("li","zhi",112);
    }
}
  • Operation results

3. Static code block loading timing (key points)

  • 1. When creating an object instance (new);

  • 2. Create a subclass object instance (new), and the parent class will also be loaded;

  • 3. When using static members of a class (static properties and static methods)

  • example

//1. Create parent class Child
public class Child {
	
    //Static code block
     static {
        System.out.println("Advertising!!!");
    }

    public static double fee = 0;
    private String name;


    public Child(String name){
        this.name = name;
    }

    public static void join(){
        fee += fee;
        System.out.println(fee);
    }
}


//2. Create subclass Son - Son inherits Child
public class Son extends Child {

    public Son(String name) {
        super(name);
    }

    public void showOut(){
        System.out.println("Subclass loaded");
    }
}


//3. Create main method to load parent class
public class main {
    public static void main(String[] args) {
        //1. Is loaded when the parent class instance is created
        //Child child1 = new Child("li");

        //2. Is loaded when a subclass instance is created
        //Son son = new Son("li");

        //3. Use static members of the parent class
        //System.out.println(Child.fee);

        //4. Use static members of subclasses
        //System.out.println(Son.fee);

        //5. Use the static method of the parent class
        //Child.join();

        //6. Static methods using subclasses
        Son.join();

    }
}
//Static code blocks can be loaded in the above six cases, but remember that static code blocks will only be loaded once!!!

4. Common code block loading timing

  • When creating an object instance, a common code block will be implicitly called and loaded once it is created;
    • Note: if you only use static members of a class, ordinary code blocks will not be executed;
//1. Create parent class - Father class
public class Father {
	//Create a normal code block
    {
        System.out.println("Advertising!!!");
    }

    public static double fee = 0;
    private String name;


    public Child(String name){
        this.name = name;
    }

    public static void join(){
        fee += fee;
        System.out.println(fee);
    }
}

//2. Create a subclass to inherit from the parent class -- Son class inherits from Child class
public class Son extends Father {

    public Son(String name) {
        super(name);
    }

    public void showOut(){
        System.out.println("Subclass loaded");
    }
}

//3. Create the main method and call the parent and child classes
public class hello {
    public static void main(String[] args) {
        //1. Is loaded when the parent class instance is created
        Father father = new Father("li");

        //2. Is loaded when a subclass instance is created
        Son son = new Son("li");
    }
}
  • Operation results

5. When creating an object, the calling sequence of a class (key and difficult points)

I. calling static code block and static attribute initialization

Note: static code blocks have the same priority as static variable initialization calls. If multiple static code blocks and static variables are initialized, they will be called in the order they define;

II. Calling the initialization of common code blocks and common attributes

Note: ordinary code blocks have the same priority as ordinary initialization calls. If there are multiple ordinary code blocks and multiple ordinary attributes initialized, they will be called in the defined order;

III. call construction method

  • example
//1. Create Child class
public class Child {
    //1. Static block code
    static {
        System.out.println("Static code block is called!!!");
    }

    //4. Common code block
    {
        System.out.println("Ordinary code block is called!!!");
    }

    //2. Static properties
    public static double fee = getfee();

    //5. Common variable
    private String name = getname();

    //7. Create constructor
    public Child(String name){
        System.out.println("Constructor call!!!");
        this.name = name;
    }
    //3. Static method
    public static int getfee(){
        System.out.println("Static method called!!!");
        return 100;
    }

    //6. Common method
    public String getname(){
        System.out.println("Ordinary method is called!!!");
        return "Common method";
    }
}



//2. Create the main method and call the Child class
public class main {
    public static void main(String[] args) {
        //1. Is loaded when the parent class instance is created
        Child child1 = new Child("li");
    }
}
  • Operation results

Keywords: Java JavaEE

Added by geo__ on Thu, 10 Feb 2022 21:11:29 +0200