📜  Java中的初始化程序块

📅  最后修改于: 2022-05-13 01:55:41.139000             🧑  作者: Mango

Java中的初始化程序块

为了在为实例数据成员赋值时执行任何操作,使用了初始化块。简单来说,初始化块用于声明/初始化类的各种构造函数的公共部分。每次创建对象时它都会运行。

初始化程序块包含在创建实例时始终执行的代码,并且在每次创建类的对象时运行。我们可以在 3 个区域使用初始化程序块:

  • 构造函数
  • 方法

示例 1:

Java
// Java Program to Illustrate Initializer Block
  
// Class
class Car {
  
    // Class member variable
    int speed;
    
    // Constructor
    Car()
    {
  
        // Print statement when constructor is called
        System.out.println("Speed of Car: " + speed);
    }
    // Block
    {
        speed = 60;
    }
    // Class member method
    public static void main(String[] args)
    {
  
        Car obj = new Car();
    }
}


Java
// Java Program to Illustrate Initializer Block
  
// Importing required classes
import java.io.*;
  
// Main class
public class GFG {
  
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println(
            "Common part of constructors invoked !!");
    }
    // Initializer block ends
  
    // Constructor 1
    // Default constructor
    public GFG()
    {
  
        // Print statement
        System.out.println("Default Constructor invoked");
    }
  
    // Constructor 2
    // Parameterized constructor
    public GFG(int x)
    {
  
        // Print statement
        System.out.println(
            "Parameterized constructor invoked");
    }
  
    // Main driver method
    public static void main(String arr[])
    {
  
        // Creating variables of class type
        GFG obj1, obj2;
  
        // Now these variables are
        // made to object and interpreted by compiler
        obj1 = new GFG();
  
        obj2 = new GFG(0);
    }
}


输出
Speed of Car: 60

示例 2:

Java

// Java Program to Illustrate Initializer Block
  
// Importing required classes
import java.io.*;
  
// Main class
public class GFG {
  
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println(
            "Common part of constructors invoked !!");
    }
    // Initializer block ends
  
    // Constructor 1
    // Default constructor
    public GFG()
    {
  
        // Print statement
        System.out.println("Default Constructor invoked");
    }
  
    // Constructor 2
    // Parameterized constructor
    public GFG(int x)
    {
  
        // Print statement
        System.out.println(
            "Parameterized constructor invoked");
    }
  
    // Main driver method
    public static void main(String arr[])
    {
  
        // Creating variables of class type
        GFG obj1, obj2;
  
        // Now these variables are
        // made to object and interpreted by compiler
        obj1 = new GFG();
  
        obj2 = new GFG(0);
    }
}
输出
Common part of constructors invoked !!
Default Constructor invoked
Common part of constructors invoked !!
Parameterized constructor invoked

有关Java中的实例初始化的更多详细信息,请参阅文章Java中的实例初始化块 (IIB)