Java 面向对象/Java 多态
在Java中重写toString()
这篇文章与Java中的Overriding equals方法类似。考虑下面的Java程序:
// file name: Main.java
class Complex {
private double re, im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
输出:
Complex@19821f
输出是类名,然后是'at'符号,以及对象的结尾hashCode。Java中的所有类从对象类继承,直接或间接地。Object类有一些基本的方法,比如clone(),toString(),equals()等.. Object中默认的toString()方法打印出“class name @ hash code”。我们可以在我们的类中重写toString()方法来打印正确的输出。例如,在下面的代码中,toString()被重写以打印“Real + i Imag”形式。
// file name: Main.java
class Complex {
private double re, im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
/* Returns the string representation of this Complex number.
The format of string is "Re + iIm" where Re is real part
and Im is imagenary part.*/
@Override
public String toString() {
return String.format(re + " + i" + im);
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
输出:
10.0 + i15.0
一般来说,当在print()或println()中使用对象时,重写toString()是一个好主意,因为我们可以得到正确的输出。