java对象属性的初始值
当我们创建一个实例时,如果没有在构造器中初始化非静态属性,编译器会将数值类型数据设为0,布尔类型数据设为false,对象类型数据设为null。
也可以通过一下方式初始化:
(1)在构造方法中初始化
(2)直接给属性默认值或调静态方法初始化。虽然PHP不能调静态方法初始化非静态属性,但是可以在构造方法中调静态方法初始化非静态属性
public class Employee { protected String name; protected double salary; protected int id = assignId(); protected static int nextId = 1; protected LocalDate hireDay; public Employee(String name, double salary, String hireDay) { this.name = name; this.salary = salary; this.hireDay = LocalDate.parse(hireDay); } public Employee(String name, double salary) { this.name = name; this.salary = salary; } public String getHireDay() { return hireDay.format(DateTimeFormatter.ofPattern("y-MM-dd")); } public String getHireDay(String DayFormatter) { return hireDay.format(DateTimeFormatter.ofPattern(DayFormatter)); } public String getName() { return name; } public int getId() { return id; } protected int assignId() { return nextId++; } }