Override toString method in Java

This article will show you about, How to Override toString method in Java. The attached example program were tested and shared below.

#1 Creating Employee class without toString() method

package com.dineshkrish;
public class Employee {
// Attributes
private int empId;
private String empName;
private double empSalary;
// setters and getters
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
}

#2 Printing the object without toString() method

package com.dineshkrish;
public class ToStringExample {
public static void main(String[] args) {
// defining the object
Employee e1 = new Employee();
// setting the attributes
e1.setEmpId(101);
e1.setEmpName("John");
e1.setEmpSalary(15000);
// printing the object
System.out.println(e1);
}
}

Output

com.dineshkrish.Employee@3ee284

#3 Overriding toString() method to Employee class

package com.dineshkrish;
public class Employee {
// Attributes
private int empId;
private String empName;
private double empSalary;
// setters and getters
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName
+ ", empSalary=" + empSalary + "$]";
}
}

#4 Printing the object with toString() method

package com.dineshkrish;
public class ToStringExample {
public static void main(String[] args) {
// defining the object
Employee e1 = new Employee();
// setting the attributes
e1.setEmpId(101);
e1.setEmpName("John");
e1.setEmpSalary(15000);
// printing the object
System.out.println(e1);
}
}

Output

Employee [empId=101, empName=John, empSalary=15000.0$]

References

1. Java Object Class
2. Java Obejct toString() method

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *