开发者

Java toString Method (objects)

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开发者_StackOverflow社区. What am I doing wrong?


Try:

public String toString(){

The code you have is adding a new method, instead of overriding the existing parameterless toString method of Object. That means the old method is still the one being called, and it gives the output you're seeing.


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 a Position to toString; it should refer the current instance.


As a complement to other posts, why do you think you need to pass Position's reference to the method toString(), anyway. After all, the method exist in the same class, Position. You can use the variable/properties directly without any reference like this.

  public String toString(){
        return "(" + x + "," + y + ")";
  }

Or in case you like to specifically have a reference then you can do it like this,

  public String toString(){
        return "(" + this.x + "," + this.y + ")";
  }

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜