繁体   English   中英

关于带参数的构造函数

[英]About constructor with parameters

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

提前致谢! =)

我很确定您可以覆盖类Point的toString()函数,使其像您希望的那样打印。 例:

@Override
public String toString() {
  return this.X + "IEATBABYCLOWNS" + this.Y;
}

假设Point不是java.awt.Point

您需要重写Point类的toString() ,因为PrintStream#println() (System.out是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;
}
 System.out.println(originOne);

这将调用该对象的类的toString方法。 而且由于您没有覆盖它,所以它调用了Object类的toString。

java.awt.Point.toString()的API描述:

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. 

如您所见,输出取决于您使用的JVM,并且不能保证获得所需的内容。

我会将println更改为:

System.out.println("[" + originOne.getX() + ", " + originOne.getY() + "]")

尝试这个

覆盖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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM