java重写 tostring_在Java中重写toString() - Break易站

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()是一个好主意,因为我们可以得到正确的输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值