How to override toString() method in Java?
Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method is used most frequently to obtain a string representation for an object. The reason for not using the same method is that this procedure was automatically invoked whenever used a print statement. Therefore, this function is overridden to return specific elements of the Object.
Example1:StringOverride.java
//Program is for overriding the toString() method in Java
//importing packages
import java.io.*;
import java.util.*;
class MethodOverride{
private double rem, imp;
public MethodOverride(double rem, double imp) {
this.rem = rem;
this.imp = imp;
}
}
// the class StringOverride to test the MethodOverride class
class StringOverride{
public static void main(String[] args) {
MethodOverride obj = new MethodOverride(100, 115);
System.out.println(obj);
}
}
Output
[email protected]
Explanation: The output consists of the class name, the "at" symbol, and the Object's hashCode at the end. In Java, all classes directly or indirectly originate from the Object class. Some fundamental functions, like clone(), function toString(), equals(), etc., are available in the Object class. "Class name @ hash code" is printed by the function toString() method's default invocation of Object. We can override our class's function toString() to produce appropriate output.
Example2: StringOverride.java
//Program for overriding the toString() method in Java
//importing packages
import java.io.*;
import java.util.*;
public class StringOverride {
// Main section of the program
public static void main(String[] args) {
// an object is created for the class
Program p1 = new Program(23,19);
// The complex number is displayed
System.out.println(p1);
}
}
// The Superclass
class Program {
// the variables of the complex number
private double real, imaginary;
// the constructor is used for declaring the default values
// the parameters are passed to the constructor
public Program(double real, double imaginary) {
// it indicates the current values of the number
this.real=real;
this.imaginary=imaginary;
}
public double getReal() {
return this. real;
}
public double getImaginary() {
return this. imaginary;
}
public void setReal(double real) {
this.real = real;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
// the toString() method is overrides
@Override
public String toString() {
return this.real + " + " + this.imaginary + "i";
}
}
Output
23.0 + 19.0i