为什么在Java中常见的做法是重写toString()方法,以打印类的实例变量?

huangapple go评论89阅读模式
英文:

Why is it common practice to override the method toString() in java to print the instance variables of the class?

问题

因为我一直在学习,甚至一些集成开发环境(IDE)中都内嵌了这个功能,可以重写 toString() 方法以打印出类的所有实例变量。

object.java 中定义的原始 toString() 如下:

public String toString() {
  return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

而通常的做法是将其重写为:

public String toString() {
  return "className{" + "var1=" + var1 + ", var2=" + var2 + '}';
}

为什么我们不保留 toString() 方法的原始功能,并创建一个新的方法(使用不同的名称)来实现这个功能呢?

英文:

As I've been learning and even some IDEs have it embeded in it, to override the toString() method to print out all instance variables of the class.

The original toString() defined in object.java is defined as follows:

public String toString() {
  return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

And it's common practice to override it as:

public String toString() {
  return "className{" +"var1="+var1+", var2="+var2+'}';
}

Why don't we keep the original functionality of the toString() method and create a new method (with a different name) with this functionality?

答案1

得分: 0

我们可以这样做。但是,那些对你的子类及其myNewToString方法一无所知的其他类,如何知道如何打印出textually represents以简洁但信息丰富的方式表示任意子类的字符串

toString方法被设计成可以被重写以实现这一点。是的,它确实有默认行为,但并不是非常有用。它的作者希望你去重写它。将其重写以返回通常做法更加有用,但你并非必须如此。一个EmailAddress类的toString方法可以返回:

public String toString() {
    return "EmailAddress{localPart = " + localPart + ", domainName = " + domainName + "}";
}

但通常返回类似这样的内容会更有用:

public String toString() {
    return localPart + "@" + domainName;
}
英文:

We could. But how will other classes, that know absolutely nothing about your subclasses with your myNewToString method, know how to print a string that textually represents, in a concise but informative way, arbitrary subclasses?

The toString method was designed to be overridden to do that. Yes, it does have default behavior but it's not very useful. Its authors wanted you to override it. Overriding it to return what's commonly practiced is more useful, but you don't have to do that. A toString method for an EmailAddress class can return

public String toString() {
    return "EmailAddress{localPart = " + localPart + ", domainName = " + domainName + "}";
}

but it's usually more useful to return something like

public String toString() {
    return localPart + "@" + domainName;
}

答案2

得分: 0

重写toString()的原因是,每当编译器将一个非String类型的对象添加到字符串中时,都会隐式调用toString()。因此,如果你有以下代码:

MyObject o = new MyObject();
C = "Hello " + o;

那么编译器将调用o.toString(),以便获得一个可以连接到"Hello "的字符串。

值得注意的是,在调用o的toString()之前,它会检查o是否为null。如果o为null,则会生成字符串"null"。

观点:toString()方法通常只应用于调试(打印/日志)的目的,在大多数情况下不应作为正常程序流程的一部分。

英文:

The reason to override toString() is that toString() is called implicit by the compiler every time an object which is not of type String, is added to a string.
So if you have

MyObject o=new MyObject();
C="Hello " + o;

Then the compiler will call o.toString() in order to get a string it can concat to "Hello "

And I should note that it checks if o is null before calling toString() on o. And if o is null, it just generate the string "null"

Opinion: The toString() method should in general and in most cases only be used for debugging (Print/Log) and not as part of the normal program flow.

huangapple
  • 本文由 发表于 2020年10月27日 22:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64557143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定