首页 > 解决方案 > 编译器不会传递构造函数的值

问题描述

嗨,我是 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

有什么问题 ?

标签: javaconstructor

解决方案


赋值是从左到右

emp_id = x;
name = y;

推荐阅读