Java似乎忽略了我的toString方法

时间:2014-05-07 04:00:45

标签: java override tostring

好的,所以我为这个Coordinate Class创建了一个toString()方法,但是当我尝试使用system.out.print()打印一个Coordinate时,它似乎忽略了我的方法而只是使用了Object.toString( )方法,只返回一个内存地址。

这是我的toString方法的代码:

package spacetable;

public class Coordinate {
private int x;
private int y;

public Coordinate(){
    x=0;
    y=0;
}
public Coordinate(int x, int y){
    this.x = x;
    this.y = y;
}

public int getX(){
    return x;
}
public int getY(){
    return y;
}

public double distTo(Coordinate xy){
    double run = xy.getX() - this.getX();
    double rise = xy.getY() - this.getX();
    double dist = sqrt(run*run + rise*rise);
    return dist;
}
public double distTo(int x, int y){
    double run = x - this.getX();
    double rise = y - this.getX();
    double dist = sqrt(run*run + rise*rise);
    return dist;
}

@Override
public String toString(){
    String Strx = Integer.toString(x);
    String Stry = Integer.toString(y);
    String result = "(" Strx + ", " + Stry + ")";
    return result;  
}

}

和我试图打印的代码:

package spacetable;
public class CordinateTest {

public static void main(String[] args) {
    Coordinate place = new Coordinate(2,3);
    System.out.println(place);
}
}

输出是: spacetable.Coordinate@e53108

为什么我的toString()会被忽略?

3 个答案:

答案 0 :(得分:1)

您的代码可以正常使用,请查看here

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{ 
    public static class Coordinate {
       private int x = 3;
       private int y = 5;

       @Override
       public String toString(){
          String Strx = Integer.toString(x);
          String Stry = Integer.toString(y);
          String result = "(" + Strx + ", " + Stry + ")";
          return result;
       }
   }

    public static void main (String[] args) throws java.lang.Exception
    {
        Coordinate place = new Coordinate();
        System.out.println(place);
    }
}

答案 1 :(得分:0)

确定在添加toString方法后重新编译了。如果您使用的是IDE,请检查是否已设置自动构建。如果没有再次构建代码

此外,您可以粘贴导入命令。只是想确保你导入自己的Coordinate类而不是某个第三方jar的类

答案 2 :(得分:-1)

public class Coordinate {
    private int x;
    private int y;
    public Coordinate(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
    public String toString()
    {

        String result = "("+ x + ", " + y + ")";
        return result;

    }
    public static void main(String[] args) {
         Coordinate place = new Coordinate(2,3);
            System.out.println(place);

    }

}