Snowman
Snowman

Reputation: 32061

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. What am I doing wrong?

Upvotes: 1

Views: 3620

Answers (4)

Adeel Ansari
Adeel Ansari

Reputation: 39897

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.

Upvotes: 2

Jayan
Jayan

Reputation: 18459

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.

Upvotes: 0

Ismail Badawi
Ismail Badawi

Reputation: 37177

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.

Upvotes: 3

sje397
sje397

Reputation: 41822

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.

Upvotes: 5

Related Questions