Overriding toString() Method in Java
Overview
The toString() method of the class returns a string representation of the object. By default, it returns the name of the class of which the object is an instance, the ‘@’ symbol, and the hash code of the object. The Hash code of the object returns an integer that represents the object’s location in the memory.
The default implementation comes from the Object class. Overriding toString() is to replace the functionality of the Object class method.
toString() method
Let’s look at the code of the method in the Object class’s definition in Java Language.
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
Example
For example, if the class Employee is located in the package name com.testingdocs
the string returned by Object’s toString() by default is:
com.testingdocs.Employee@memoryAddressLocation
Code Listing
The toString() is a method that all classes inherit from the Object super class in Java. Generally, this method is overridden in order to print informative output describing the object’s state.
We use the @Override annotation to indicate that a method is intended to override a method in a superclass.
/** * */ package com.testingdocs.demo; /** * @author testingdocs * Sample class to demo overridden toString() method. * www.TestingDocs.com */ public class JavaTutorial { private String coursename; public JavaTutorial(String coursename) { this.coursename = coursename; } //setter and getter public String getCoursename() { return coursename; } public void setCoursename(String coursename) { this.coursename = coursename; } @Override public String toString() { return getClass().getName() + "\n" + "Course Name:=" + this.getCoursename(); } /** * @param args * Main method */ public static void main(String[] args) { JavaTutorial jt = new JavaTutorial("Java 14 Course"); System.out.println(jt); } }
Notice that toString() is called automatically on the object by the System.out.println() statement.
System.out.println(obj)
System.out.println(obj.toString())
Both the statements are same. Both statements print the object state to the console.
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :