在Java中重写toString()方法

Java是面向对象的,它只处理类和对象。如果我们确实需要任何计算,我们会使用与类对应的对象的帮助。它是Java最常用的获取对象字符串表示的方法。现在你一定想知道,直到现在,他们还没有使用相同的系统,而是在控制台上获得字符串表示或简短的输出。出来打印这是因为在编写print语句时自动调用了该方法。因此,这个方法被重写,以便返回下面通过示例显示的对象的值。

null

例1:

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@214c265e

输出说明: 输出是 类名,然后是“at”符号,最后是 哈希码 属于 这个 对象 .Java中的所有类都直接或间接地继承自对象类(请参见本文第1点) ).对象类有一些基本方法,如clone()、toString()、equals()、等,。。等等。对象中的默认toString()方法打印“class name@hash code”。我们可以重写类中的toString()方法来打印正确的输出。例如,在下面的代码中,toString()被重写以打印 “真实+图像” 类型

例2:

JAVA

// Java Program to illustrate Overriding
// toString() Method
// Class 1
public class GFG {
// Main driver method
public static void main(String[] args) {
// Creating object of class1
// inside main() method
Complex c1 = new Complex( 10 , 15 );
// Printing the complex number
System.out.println(c1);
}
}
// Class 2
// Helper class
class Complex {
// Attributes of a complex number
private double re, im;
// Constructor to initialize a complex number
// Default
// public Complex() {
//     this.re = 0;
//     this.im = 0;
// }
// Constructor 2: Parameterized
public Complex( double re, double im) {
// This keyword refers to
// current complex number
this .re = re;
this .im = im;
}
// Getters
public double getReal() {
return this .re;
}
public double getImaginary() {
return this .im ;
}
// Setters
public void setReal( double re) {
this .re = re;
}
public void setImaginary( double im) {
this .im = im;
}
// Overriding toString() method of String class
@Override
public String toString() {
return this .re + " + " + this .im + "i" ;
}
}


输出

10.0 + 15.0i

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享