欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实例域初始化方法及顺序

程序员文章站 2023-02-17 16:44:19
java实例域初始化方式1.构造器public class employee { private string name; private string gender; private int...

java实例域初始化方式

1.构造器

public class employee {
  private string name;
  private string gender;
  private int age;
  private double salary;

  public employee() {
    this.salary = 1000.0;
  }

  public employee(string name, string gender, int age, double salary) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.salary = salary;
  }
}

2.域声明

public class employee {
  private string name;
  private string gender;
  private int age;
  private double salary = 1000.0;

  public employee() {
  }
  public employee(string name, string gender, int age, double salary) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.salary = salary;
  }
}

3.初始化块(initialization block)

public class employee {
  private string name;
  private string gender;
  private int age;
  private double salary;
  private static string test;

  //静态初始化块:类第一次被加载时执行
  static {
    system.out.println("类加载");
    test = "hello world!"
  }
  
  //初始化块
  {
    name = "xiao";
    gender = "m";
    age = 20;
    salary = 1000.0;
    system.out.println("初始化");
  }

  @override
  public string tostring() {
    return "employee{" +
        "name='" + name + '\'' +
        ", gender='" + gender + '\'' +
        ", age=" + age +
        ", salary=" + salary +
        '}';
  }
  public static void main(string[] args) {
    employee employee = new employee();
    system.out.println(employee.tostring());
  }
}

初始化
employee{name='xiao', gender='m', age=20, salary=1000.0}
process finished with exit code 0

java实例域初始化顺序

调用构造方法的具体处理步骤:

1. 如果类是第一次被使用,先执行静态初始化块

2. 所有数据域被初始化为默认值(0、false或null)

3. 按照在类声明中出现的次序,依次执行所有域初始化语句和初始化块。

4. 如果构造方法调用了其他构造方法,先执行其他方法。

5. 最后,执行构造方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。