在Java中,toString()方法的确切目的是什么?

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

What exactly is the purpose of a toString() method in Java?

问题

最近我在一个项目中使用了toString()方法来整理控制台输出,但我想知道这个方法是否有任何特殊意义,而不仅仅是简单地返回一个字符串?

英文:

I recently used a toString() method in one of my projects to organize the output in my console but I was wondering if there is any significance to this method rather than it simply returning a string?

答案1

得分: 1

有几个理由可以使用 toString() 方法。重要的是,所有对象都内置了这个方法,因此它允许你将一个对象(比如一个整数 Integer)连接到一个字符串。有时候,你可以通过将一个空字符串附加到该对象上来实现这一点(例如 "" + my_int 将产生一个字符串),因为在底层 Java 会调用 my_int 的 toString() 方法来转换它。

当处理更复杂的自定义对象时,它也非常有用。假设你定义了一个名为 Classroom 的对象,其中包括几个不同的成员变量,包括整数、布尔值和列表。如果你想要将一个 Classroom 对象打印到控制台,它会是什么样子?你可以重写 toString() 方法来定义一个 Classroom 对象的字符串表示形式应该是什么样子。(例如,也许你想要打印教室中学生的列表,或者教室的教室号码、教师的名字等等。)

英文:

There are several reasons to use a toString() method. The important thing is that all objects have one natively, so it allows you to concatenate an object (such as an Integer) to a string. Sometimes you can do this just by appending an empty string to that object (e.g. "" + my_int will produce a string) because under the hood Java calls my_int's toString() method to convert it for you.

It's also useful when dealing with more complicated custom objects. Let's say you define an object Classroom with several different member variables, including ints, bools, and lists. If you went to print a Classroom object to console, what would it look like? You would override the toString() method to define what you would want a Classroom object's string to look like. (E.g. maybe you would want it to print the list of students in the classroom, or the classroom's room number or teacher's name, etc.)

答案2

得分: 0

toString方法在你需要将一个对象转换为字符串时被调用,例如当你想要打印它时。

英文:

toString is called whenever you need to convert an object to a String, e.g. when you want to print it.

huangapple
  • 本文由 发表于 2020年8月30日 07:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63652796.html
匿名

发表评论

匿名网友

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

确定