Java toString 方法(对象)
class Position {
private double x,y;
private int id;
public String toString(Position a){
String words ="(" + a.x + "," +a.y + ")";
return words;
所以我在这里返回了一个内存地址。我做错了什么?我想获取使用 setter 设置的 x 和 y 的实际值。我也有吸气剂,我尝试不把 ax 放在 getX() 上,但这仍然给了我另一个内存地址。我做错了什么?
class Position {
private double x,y;
private int id;
public String toString(Position a){
String words ="(" + a.x + "," +a.y + ")";
return words;
So I'm getting a memory address returned here. What am I doing wrong? I want to get the actual values of x and y that were set using setters. I also have getters, and I tried instead of putting a.x putting getX(), but that still give me another memory address. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
您拥有的代码正在添加一个新方法,而不是覆盖
Object
现有的无参数toString
方法。这意味着旧方法仍然是被调用的方法,并且它给出了您所看到的输出。Try:
The code you have is adding a new method, instead of overriding the existing parameterless
toString
method ofObject
. That means the old method is still the one being called, and it gives the output you're seeing.您实际上并没有重写 toString ;相反,您通过定义一个具有相同名称但需要不同参数的方法来重载它。您没有将
Position
传递给toString
;它应该引用当前实例。You're not actually overriding
toString
; rather, you're overloading it by defining a method with the same name but which expects different arguments. You don't pass aPosition
totoString
; it should refer the current instance.作为对其他帖子的补充,您为什么认为需要将
Position
的引用传递给toString()
方法。毕竟,该方法存在于同一个类Position
中。您可以直接使用变量/属性,而无需像这样的任何引用。或者,如果您想专门有一个参考,那么您可以这样做,
我在重构后将该方法制作为一个衬里。
如果您有兴趣了解人们更喜欢哪个版本,请参阅 这里,什么时候使用
this
。这是关于Java 中重写如何工作的教程/说明。As a complement to other posts, why do you think you need to pass
Position
's reference to the methodtoString()
, anyway. After all, the method exist in the same class,Position
. You can use the variable/properties directly without any reference like this.Or in case you like to specifically have a reference then you can do it like this,
I made the method one liner after refactoring.
In case you are interested in knowing which version folks like more, please refer to here, when to use
this
. And here is the tutorial/explanation on how overriding works in Java.由于这是一项作业,我会要求您单步调试调试器。即使您期望它这样做,您的方法也不会被调用。 ( toString() 和 toString(Someobject ) 是不同的。
Since it is a homework, I would ask you step through a debugger. Your method is not called even though you expect it do so. ( toString() and toString(Someobject ) are different.