【问题标题】:Incorrect output even with setters in java即使在java中使用setter,输出也不正确
【发布时间】:2014-12-20 20:55:38
【问题描述】:
public class Employee {
private String name;
private String jobTitle;
private String department;
private float salary;

public Employee(String name, String jobTitle, String department, float salary){
name = "";
jobTitle = "";
department = "";
salary = 0;
}

public void setName(String name) {
    this.name = name;
}
public void setJobTitle(String jobTitle){
    this.jobTitle = jobTitle;
}
public void setDepartment(String department){
    this.department = department;
}
public void setSalary(float salary){
    this.salary = salary;
}
public String getName(){
    return name;
}
 public String getJobTitle(){
    return jobTitle;
}
  public String getDepartment(){
    return department;
}
   public float getSalary(){
    return salary;
}
   public double incrementSalary() {
       return ((salary/100)*2)+ salary;


}
}

我的测试课

public class EmployeeTest {
public static void main(String[] args){

Employee employee1 = new Employee("jack","management","ccl",2567);
System.out.println(employee.getSalary());



}

}

嗨,刚开始学习 java,我无法获得正确的输出,它应该超出 2567 的薪水,但我一直得到默认值 0。我已经搞砸了,但一直得到 null 和 0s 有什么想法吗?

【问题讨论】:

  • 嗯。当您在测试类中调用new Employee() 时,该调用什么方法?那个方法有什么作用?
  • 修复你的构造函数

标签: java class constructor output


【解决方案1】:

问题是你的构造函数什么都不做。你应该使用this.name = name

【讨论】:

    【解决方案2】:

    你的构造函数没有设置任何值 它应该看起来像

    public Employee(String name, String jobTitle, String department,
            float salary) {
        this.name = name;
        this.jobTitle = jobTitle;
        this.department = department;
        this.salary = salary;
    }
    

    【讨论】:

      【解决方案3】:

      改变

      public Employee(String name, String jobTitle, String department, float salary){
          name = "";
          jobTitle = "";
          department = "";
          salary = 0;
      }
      

      public Employee(String name, String jobTitle, String department, float salary){
          this.name=name;
          this.jobTitle=jobTitle;
          this.department=department;
          this.salary=salary;
      }
      

      【讨论】:

        猜你喜欢
        • 2022-08-15
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多