JAVA construction code block and partial code block

JAVA construction code block and partial code block


Form: { code... }

construct code block

Features of Constructing Code Blocks

位置: 在类的内部,在方法的外部
作用: 用于抽取构造方法中的共性代码
执行时机: 每次调用构造方法前都会调用构造代码块
注意事项: 构造代码块优先于构造方法加载

/**
* Construction code block: {}
*1. Location: outside the method in the class
* 2. Execution timing: Every time an object is created, the construction code block will be executed, and it will be executed prior to the construction method
* 3: Function: for Extract the common functions of all construction methods
*/

package cn.tedu.oop2;
/**本类用于测试代码块*/
public class TestBlock {
    
    
    public static void main(String[] args) {
    
    
//        System.out.println("今天特别冷,注意保暖");
        Pig p = new Pig();
        Pig p2 =new Pig();
        Pig p3 = new Pig(666);
        Pig p4  =new Pig("xxxx");
    }

}
//1.创建一个小猪类用来测试
class Pig{
    
    
    //2.定义属性
    String food;//食物
    int age;//年龄
    //5.创建本类的构造代码块
    //4.提供本类的无参构造

    /**
     * 构造代码块:{
    
    }
     *1.位置:类里方法外
     * 2.执行时机:每次创建对象时,都会执行构造代码块,并且优先于构造方法执行
     * 3:作用:用于提取所有构造方法的共性功能
     */
    {
    
    
        System.out.println("我是一个构造代码块");
        System.out.println("咱可是黑猪肉222~");
    }
    //4.提供本类的无参构造与含参构造
    public Pig(){
    
    
        System.out.println("无参构造");

    }

    public Pig(int n){
    
    
        System.out.println("含参构造1");
    }

    public Pig(String n){
    
    
        System.out.println("含参构造2");
    }
    //3.定义普通方法
    public void eat(){
    
    
        System.out.println("小猪爱吃菜叶子");
    }
}

insert image description here

local code block

Position: The code block in the method
Function: Usually used to control the scope of the variable, and it will be invalid if the curly braces are out.
Note: The smaller the scope of the variable, the better, and member variables will have thread safety

Exercise: Test the loading order of code blocks
Execution order: Construction code block -> Construction method -> Common method -> Local code block

  • 1. When an object is created, the constructor is triggered
  • 2. When creating an object, the construction code block is also triggered, and the construction code block is executed prior to the construction method
  • 3. After we create the object, we can call the ordinary method through the object
  • 4. If there is a local code block in the common method, the corresponding local code block will be triggered

Guess you like

Origin blog.csdn.net/weixin_46411355/article/details/130039781