【发布时间】:2018-02-09 13:08:45
【问题描述】:
Java 新手并尝试设置 get 和 set 方法。尽管我需要根据 getSalary() 乘以 getMonths() 来计算年初至今的总数。
我无法确定是否可以在 get 或 set 方法中进行计算,或者我可能只是一个新手,我把它放在错误的地方。
public class Employee_v2
{
//Instance variables
private String first_name;
private String last_name;
private double salary;
private int months;
final double increase= 0.25;
private double year_to_date;
public Employee_v2()
{
//fill in the code to set default values to the instance variables
first_name="";
last_name="";
salary= 0.0;
months= 0;
}
//Constructor initializing instance variables with arguments
public Employee_v2(String f, String l, Double sal, int mo)
{
first_name = f;
last_name = l;
salary = sal;
months = mo;
}
//set arguments
public void setFirst(String f)
{
first_name = f;
}
public void setLast (String l)
{
last_name = l;
}
public void setSalary (double sal)
{
salary = sal;
}
public void setMonths (int mo)
{
months = mo;
}
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
//get arguments
public String getFirst()
{
return first_name;
}
public String getLast()
{
return last_name;
}
public double getSalary()
{
return salary;
}
public int getMonths()
{
return months;
}
public double getYtdSalary()
{
return yearToDateSal;
}
//DISPLAY
public void displayEmployee()
{
//display the name and salary of both Employee objects
System.out.println("Employee first name: " + getFirst());
System.out.println("Employee last name: " + getLast());
System.out.printf("Employee salary: $%.2f\n", getSalary());
//complete the code
System.out.println("-------------------------------");
//Determine the year to date salary for both employee
System.out.printf(getFirst() + "'s salary: $%.2f\n", getSalary());
// System.out.println(jas.getSalary());
System.out.printf("Year to date salary: $%.2f\n", getYtdSalary());
//set and display salary with increase
setSalary(getSalary()+ getSalary()*increase);
System.out.printf("New Salary: $%.2f\n", getSalary());
System.out.println();
System.out.println();
}//end method
}//end Class
【问题讨论】:
-
有错误吗?
-
如果它可以编译就意味着你可以。公开集合方法和一般的可变性是不受欢迎的。除了在 set 方法中设置值之外,还可以做任何事情。我看不出有一个公共的“setYtdSalary()”方法的意义,在getter中这样做......
-
约定是通过驼峰式命名您的 getter 和 setter 实例变量。例如 setFirst 是错误的(实例变量应该是“first”而不是 first_name)。您的 IDE 可以为您的 getter 和 setter 生成代码
-
Stack Overflow 是针对非常具体的狭隘问题的。请说明您的确切问题。
-
@BasilBourque 似乎足够具体,可以很快解决问题。感谢您的意见。