Is there a way to make toString()
include private fields of the super class
? I tried adding a super.toString()
, no use however.
Please see the code below
Employee.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());
}
}
Manager.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 + "]";
}
}
Output
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
That was the best i could do , to concatenate super.toString()
+' a set of Strings', surely this is messy , is there some other way , even if the language spec does not allow it does eclipse have some facility to do that , NOTE: I used eclipse to generate the toString method , any way by which i can tell eclipse to include the super class fields too,
In other words can i replace this messy code
return(this.getClass().getName()+" ["+super.toString().substring((this.getClass().getSuperclass().getName().length()-3
), (super.toString().length())-1)+", bonus="+bonus+"]");
by getting eclipse to automate the process and generate a suitable way to do it?