我有一个关于构造函数的问题,如果我创建一个像这样的构造函数:
Point originOne = new Point(23, 94);
如果我理解正确,originOne 将指向 23 和 94。当我尝试使用 System.out.println(originOne) 打印它时,我没有得到这些值,怎么会?
提前致谢!=)
我有一个关于构造函数的问题,如果我创建一个像这样的构造函数:
Point originOne = new Point(23, 94);
如果我理解正确,originOne 将指向 23 和 94。当我尝试使用 System.out.println(originOne) 打印它时,我没有得到这些值,怎么会?
提前致谢!=)
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;
}
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.
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() + "]")
假设Point
不是java.awt.Point
。
您需要重写toString()
类,因为(System.out is a )Point
的重载方法之一将对象作为参数,使用对象获取对象的字符串表示形式,然后打印它:PrintStream#println()
PrintStream
toString()
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;
}
尝试这个
覆盖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;
}
}
尝试这个:
System.out.println(originOne.getX() + " " + originOne.getY());