Java / Strings
Overriding toString() example.
In the above Employee example, overriding toString() method makes clean and understandable result.
package org.javatutorials.StringBased; public class Employee { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Employee name: " + getFirstName() + " " + getLastName() + " and his age: " + age; } public static void main(String[] args) { Employee emp = new Employee(); emp.setFirstName("Kelly"); emp.setLastName("Scott"); emp.setAge(40); System.ot.println(emp); } }
Output: Employee name: Kelly Scott and his age: 40
More Related questions...