1

我有一个关于构造函数的问题,如果我创建一个像这样的构造函数:
Point originOne = new Point(23, 94); 如果我理解正确,originOne 将指向 23 和 94。当我尝试使用 System.out.println(originOne) 打印它时,我没有得到这些值,怎么会?

提前致谢!=)

4

6 回答 6

2

I'm pretty sure you can override the toString() function of your class Point to make it print just like you want it to. Example:

@Override
public String toString() {
  return this.X + "IEATBABYCLOWNS" + this.Y;
}
于 2013-11-04T09:58:37.423 回答
0
 System.out.println(originOne);

This calls the toString method of the class of that object. And since you didnt override it, it calls the toString of the Object class.

于 2013-11-04T09:57:46.697 回答
0

API description of java.awt.Point.toString():

Returns a string representation of this point and its location in the (x,y) 
coordinate space. This method is intended to be used only for debugging 
purposes, and the content and format of the returned string may vary between 
implementations. The returned string may be empty but may not be null. 

As you can see, the output depends on which JVM you use, and you are not guaranteed to get what you want.

I would change the println to something like:

System.out.println("[" + originOne.getX() + ", " + originOne.getY() + "]")
于 2013-11-04T09:58:24.247 回答
0

假设Point不是java.awt.Point

您需要重写toString()类,因为(System.out is a )Point的重载方法之一将对象作为参数,使用对象获取对象的字符串表示形式,然后打印它:PrintStream#println()PrintStreamtoString()

java.io.PrintStream#println(Object)

public void println(Object x) {
     String s = String.valueOf(x);
     synchronized (this) {
         print(s);
         newLine();
     }
}

java.lang.String#valueOf(Object)

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

覆盖类就像在其中添加方法及其实现一样简单:

@Override
public String toString() {
    return "x = " + x + " - y = " + y;
}
于 2013-11-04T09:57:32.073 回答
0

尝试这个

覆盖toString方法。请参阅下面的案例

        package test;

        public class Point {

    private int x;
    private int y;

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

   public static void main(String[] args) {

    Point point = new Point(23, 94);

    System.out.println(point);
    }

    @Override
  public String toString() {
    return "x : " + x + " y: "+ y;
   }
 }
于 2013-11-04T10:02:29.347 回答
0

尝试这个:

System.out.println(originOne.getX() + " " + originOne.getY());
于 2013-11-04T10:03:20.287 回答