【问题标题】:toString() with and without parameter带参数和不带参数的 toString()
【发布时间】:2021-01-18 21:44:52
【问题描述】:

我不知道如何编写我的toString() 方法。

这是我的 Main.java

Dice d = new Dice();
System.out.println(d);

d= new Dice(3);
System.out.println(d);

我的toString()方法应该怎么写,需要写两个toString()的吗?

我的Dice()

public class Dice {

    private double kz= Math.random() * (6 - 1) + 1;
    private double mz;

    public Dice() {
        this.kz= Math.random() * (6 - 1) + 1;
    }

    public Dice(double n) {
        this.mz= n;
    }

    public String toString() {
            return String.format("%.0f", this.kz);
    }

}

这个我试过了,还是不行

public String toString(double i) {
    return String.format("%.0f", this.mz);
}

【问题讨论】:

  • 两个toString()是什么意思?
  • 不清楚您期望带有参数的版本做什么,或者您为什么会这样写。但一般来说,要覆盖方法,您的方法需要与您要覆盖的方法具有相同的签名。从 Object.toString() 的定义中可以看出,这意味着没有参数。

标签: java tostring


【解决方案1】:

您可以使用相同的成员,而不是为两个构造函数使用两个单独的成员。这样,您的 toString 方法就不需要尝试找出对象是如何构造的:

public class Dice {

    private double kz;

    public Dice() {
        this(Math.random() * (6 - 1) + 1);
    }

    public Dice(double n) {
        this.kz = n;
    }

    public String toString() {
        return String.format("%.0f", this.kz);
    }
}

【讨论】:

    【解决方案2】:

    toString() 方法是大多数内置 java 类调用的默认方法,它是作为字符串返回对象信息的标准。

    你的方法:

    public String toString(double i) {
        return String.format("%.0f", this.mz);
    }
    

    不起作用,因为按照惯例,像 Stystem.out.println() 这样的方法会寻找标准签名,而不是奇怪的 toString(doulbe foo)

    如果您想在方法调用时查看对象状态,可以执行以下操作:

    public String toString(double i) {
        return String.format("kz = %.0f, mz = %.0f, ", kz, mz);
    }
    

    您可以对 Dice 类进行一些调整:

    • 你也可以省略 this 关键字,当你想引用你所在的同一个对象或者有这样的冲突时你必须使用:
      public class Dice {
      
          private double foo;
      
          // If you try to remove this. you will get a runtime error
          public Dice(double foo) {
              this.foo = foo;
          }
      }
      
    • 你只能有一个变量和多个自己调用的构造函数(归功于Mureinik's answer):
      public class Dice {
          private double kz;
      
          public Dice() {
              this(Math.random() * (6 - 1) + 1);
          }
      
          public Dice(double n) {
              this.kz = n;
          }
      }
      

    【讨论】:

      猜你喜欢
      • 2017-06-19
      • 1970-01-01
      • 2011-08-07
      • 2021-04-16
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多