是的,这是一个有效的 toString 方法,它将返回一个包含学生对象所有属性的字符串表示形式。

例如,以下代码展示了如何在 Student 类中实现 toString() 方法:

public class Student {
  private int id;
  private String name;
  private int eng;
  private int math;
  private int comp;
  private int sum;

  // 省略其他代码...

  @Override
  public String toString() {
    return 'Student [id=' + id + ', name=' + name + ', eng=' + eng + ', math=' + math + ', comp=' + comp + ', sum=' + sum + ']';
  }
}

当您调用 student.toString() 时,它将返回一个类似于以下的字符串:

Student [id=123, name='John Doe', eng=80, math=90, comp=75, sum=245]

这个字符串清晰地显示了学生对象的所有属性及其值。

注意:

  • toString() 方法应该返回一个易于理解和可读的字符串。
  • 它通常包含对象的所有主要属性及其值。
  • 您可以根据需要自定义格式。
Java toString() 方法:格式正确性与示例

原文地址: https://www.cveoy.top/t/topic/oWcL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录