如何打印新对象的参数?

How to print parameters of new object?

我不明白Java中的一些例子。

public class Pair {
  private int a;
  private int b;
  public Pair(){

  }

  public Pair(int x, int y) {
    a = x;
    b = y;
  }

}

第二个class

   public class First extends Pair {
     public First(int x, int y) {
       super(x,y);
     }

     public static void main(String[] args) {
       Pair pair = new Pair(10,11);
       String s = "It is equal " + pair;
       System.out.println(pair);
     }

 }

因为它使用了字符串连接,所以它会自动从 class 对中调用方法 toString(), 所以结果应该是:"It is equal (10,11)"。 它打印我在内存中的位置,为什么?
也许我应该像这样调用方法:

public void show(){
System.out.println(a + "" + b);
}

但是在示例中没有方法 show(),只有上面的 String。

由于您没有重写 class 的 ToString() 方法,它将调用对象 class toString() ,它本身会为您提供对象的内存位置。

所以解决方案是您必须覆盖 class 中的 toString() 并将所需的代码段放在那里,以便在打印对象引用时。将调用您覆盖的 toString() 并显示预期结果。

谢谢

这是正确的,因为 jvm 从对象 class 调用 toString 的默认实现,打印身份哈希码。如果你想要这样的输出,那么你可以覆盖 Pair class 中的 toString() 方法,如下所示:

@Override
protected String toString{
    return "("+a+","+b+")";
}

执行此操作后,您将获得预期的结果,因为您已覆盖 toString() 方法。

It's recommended approach to override the toString method as it helps in debugging and provide the meaningful logs.

在你的 Pair class 中用你预期的结果覆盖 toString。 喜欢

@Override
    public String toString() {
        int c=a+b;
        return "Pair =" + c;
    }