Help the world stop coronavirus! Stay home!

Prev Next

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

❤Cash Back At Stores you Love !!!❤

Earn your $10 reward when you make your first purchase through Ebates by signing up with clicking below button.

Ebates Coupons and Cash Back

More Related questions...

Show more question and Answers...

Using String

Comments & Discussions