如何从对象Java获取信息?我可以更简化代码吗?

时间:2017-02-19 12:55:04

标签: java object methods constructor

我被分配了一个项目来创建一个类,并使用方法而不编辑" EmployeeTester"类。我怎样才能从哈利的对象中获取名称,而不是设置名称="哈利"?我还可以更简化我的代码吗?

public class EmployeeTester
    {
        /**
         * main() method
         */
        public static void main(String[] args)
        {
            Employee harry = new Employee("Hacker, Harry", 50000.0);**\\
            harry.raiseSalary(25.0);    // Harry gets a 25 percent raise!

            System.out.println(harry.getName() + " now makes " +
                                                      harry.getSalary());
        }

    }



public class Employee
{
    // instance variables 
    private double salary;
    private String name;
    /**
     * Constructor for objects of class Employee
     */
    public Employee(String employeeName, double currentSalary)
    {
        //Initializes instance variables
        salary = currentSalary;
        name = employeeName;
    }
    public String getName()
    {
        //Sets name to harry
        name = "Harry";
        return name;
    }
        public void raiseSalary(double byPercent)
    {
        //multiplies by 1.25 percent to get the 25% raise
        salary = salary *(1 + byPercent/100);
        return;
    }
    public double getSalary()
    {
        //returns the salary
        return salary;
    }
}

1 个答案:

答案 0 :(得分:1)

可以是这样的

class Employee
{
   private double salary;
   private String name;

   public Employee(String titleName, double salary) {
    this.name = titleName.split(",")[1];
    this.salary =salary;
   }

   public void raiseSalary(double byPercent) {
      salary = salary *(1 + byPercent/100);
   }

   public String getName() {
      return name;
   }

   public double getSalary() {
      return salary;
   }
}