嗨,我是Java的新手,试图学习基础知识,我一直在研究构造函数方法并遇到问题
public class Employee {
int emp_id;
String name;
String Depart;
double Salary;
double bonus;
boolean resident;
public Employee() {
emp_id = 1;
name = "null";
Depart = "General";
Salary = 0.0;
bonus = 0.0;
resident = true;
}
public Employee(int x , String y) {
x = emp_id;
y = name;
}
public Employee(int x , String y , boolean b) {
this (x,y);
b = resident;
}
public void print_emp() {
System.out.println("Employee name = "+ name +"\nHis ID is : " + emp_id + "\nHis department is : "+ Depart + "\nResidency = " + resident + "\nHis salary = "+Salary);
}
public static void main(String[] args) {
Employee e1 = new Employee(20,"Ali");
e1.set_dept("Auto");
e1.print_emp();
}
}
当我尝试打印时,它只是为我提供了默认的构造函数值:
Employee name = null
His ID is : 0
His department is : null
Residency = false
His salary = 0.0
出什么问题了?
答案 0 :(得分:2)
分配是从左到右
emp_id = x;
name = y;
答案 1 :(得分:0)
在这两个构造函数中,您可以向后进行赋值操作:
public Employee(int x , String y) { x = emp_id; y = name; } public Employee(int x , String y , boolean b) { this (x,y); b = resident; }
分配是从左到右的,因此应该这样写:
public Employee(int x , String y) {
emp_id = x;
name = y;
}
public Employee(int x , String y , boolean b) {
this (x,y);
resident = b;
}