类构造函数未正确初始化值

时间:2015-10-02 00:52:17

标签: java constructor

我有一个主java文件和一个员工类。对于员工类,我有3种方法 - getName方法返回employee namegetSalary方法返回salaryraiseSalary提出salary一定百分比。

在我的Main.java文件中,我创建了一个构造函数来初始化employee类的值,当我尝试打印出这些值时,我得到null和0

/**
 * This class tests the Employee object.
 * 
 */
public class Main {
    /**
     * Create an employee and test that the proper name has been created. Test
     * the initial salary amount and then give the employee a raise. Then check
     * to make sure the salary matches the raised salary.
     * 

    public static void main(String[] args) {
        Employee harry = new Employee("Hi", 1000.00);
        System.out.println("Employee name:" + harry.getName());
        System.out.println("Salaray: "+ harry.getSalary());

        harry.raiseSalary(10); // Harry gets a 10% raise.
    }
}

/*** This class implements an employee which is a person with a name and a      salary.
* 
*/
public class Employee {

    private String employeeName;
    private double currentSalary;

    public Employee(String employeeName, double currentSalary) {

    }

    // Accessors that are obvious and have no side effects don't have to have
    // any documentation unless you are creating a library to be used by other
    // people.
    public String getName() {
        return employeeName;
    }

    public double getSalary() {
        return currentSalary;
    }

    /**
     * Raise the salary by the amount specified by the explicit argument.
     * 
     */
    public void raiseSalary(double byPercent) {
        currentSalary = getSalary() * byPercent;
    }
}

1 个答案:

答案 0 :(得分:0)

构造函数中的参数不指向在其范围之外创建的相同对象...只需修复

public Employee(String employeeName, double currentSalary) {
this.employeeName = employeeName;
this.currentSalary = currentSalary;

}

添加"这个"在变量名之前,只需告诉代码指向范围之外的变量