java类构造函数未正确初始化值
我有一个主java文件和一个employee类。对于employee类,我有3个方法—返回employee name
的getName
方法、返回salary
的getSalary
方法和将salary
提高一定百分比的raiseSalary
在我的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 楼答案
构造函数中的参数不指向在其作用域之外创建的相同对象。。。简单地修复
在变量名之前添加一个“this”,只需告诉代码指向作用域之外的变量