views:

52

answers:

4
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?

+4  A: 

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.

sje397
Ok that did the trick, but I'm still not understanding why it does not take any parameters?
fprime
`Object.toString()` does not take any parameters, therefore the method you write to override it must not. Consider this: `public String toString(Position a){ return "(" + a.x + "," +a.y + ")"; } public String toString(){ return toString(this); }`
Supuhstar
@fprime: the function is a method of the `Position` class. When you call a method, `this` points to the instance you call the function on. If you have e.g. `Position p = new Position(); p.toString();` the `toString` method acts on `p` - so no need to pass it a Position instance.
sje397
More than just the name, a method's type of params, # of params, order, etc are all part of it's signature http://download.oracle.com/javase/tutorial/java/IandI/override.html
Kevin Zhou
+3  A: 

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.

isbadawi
A: 

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.

Jayan
+2  A: 

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.

Adeel Ansari