如何使 toString() 方法同时返回超类私有字段及其实例字段?
有没有办法让包括私人领域的超级?我尝试添加一个,但是没有用。toString()
class
super.toString()
请参阅下面的代码
员工.java
package test;
public class Employee {
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
super();
this.name = name;
this.id = id;
this.salary = salary;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary
+ "]";
}
public static void main(String[] args) {
Employee e=new Employee("Joe", 14, 5000);
System.out.println(e);
Manager m=new Manager("Bill", 23, 5000, 10);
System.out.println(m);
System.out.println("Employee Salary is "+e.getSalary()+"\nManager salary is "+m.getSalary());
}
}
经理.java
package test;
public class Manager extends Employee{
private double bonus;
public Manager(String name, int id, double salary,int bonus) {
super(name, id, salary);
this.bonus=bonus;
}
public double getSalary()
{
double baseSalary=super.getSalary();
return (baseSalary+baseSalary*(bonus/100));
}
@Override
public String toString() {
return(this.getClass().getName()+" ["+super.toString().substring((this.getClass().getSuperclass().getName().length()-3
), (super.toString().length())-1)+", bonus="+bonus+"]");
//didn't work
//super.toString();
//return "Manager [bonus=" + bonus + "]";
}
}
输出
Employee [name=Joe, id=14, salary=5000.0]
test.Manager [name=Bill, id=23, salary=5000.0, bonus=10.0]
Employee Salary is 5000.0
Manager salary is 5500.0
这是我能做的最好的,连接+'一组字符串',当然这很混乱,还有其他方法,即使语言规范不允许它确实eclipse有一些工具可以做到这一点,注意:我使用eclipse来生成toString方法,任何我可以告诉eclipse包括超类字段的方法,super.toString()
换句话说,我可以替换这个混乱的代码吗?
return(this.getClass().getName()+" ["+super.toString().substring((this.getClass().getSuperclass().getName().length()-3
), (super.toString().length())-1)+", bonus="+bonus+"]");
通过获取 eclipse 来自动化该过程并生成合适的方法来执行此操作?