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

网友投稿 293 2022-12-08


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

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 + '\'' +

http:// ", 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. 最后,执行构造方法。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java Switch对各类型支持实现原理
下一篇:Java substring方法实现原理解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~