Override toString() method of Class
To override default toString() method of a class in Java, define a public method in the class with the name toString(), no parameters, and return type String.
By default every class in Java is derived from Object class. In Object class, toString() method is defined to display the class name followed by @ hash code. We can override this toString() method by having an exact declaration of return type, method name, and no parameters (as in original method).
Example
In the following example, we define a class Address with two properties: state, country, zip. We override the toString() method in this Address class to display the Address object as shown in the following.
State : SSS
Country : CCC
ZIP : NNN
toString() method of Address object is called when the Address object is interpreted as a String, as in for example, if we pass the Address object as an argument to System.out.println(), or concatenate Address object to a String, etc.
Example.java
class Address {
String state;
String country;
String zip;
public Address(String state, String country, String zip) {
this.state = state;
this.country = country;
this.zip = zip;
}
public String toString() {
return "State : " + this.state + "\n" +
"Country : " + this.country + "\n" +
"ZIP : " + this.zip;
}
}
public class Example {
public static void main(String[] args) {
Address address = new Address("California", "United States", "90201");
System.out.println(address);
}
}
B.java
State : California
Country : United States
ZIP : 90201