Java:为什么我的 toString 方法打印错误信息?

Ang*_*mar 3 java overriding subclass tostring superclass

我有一个抽象超类,它有两个属性:int 和 string。我已经覆盖了其中的 toString 方法及其具有一个额外属性 (LocalDate) 的子类。但是,由于某种我不明白的原因,当我打印子类 toSring 信息时,int 值会发生变化。

这是我在超类中的内容:

public abstract class File {
private int id;
private String text;

public File(int newId, String newText) throws IllegalArgumentException {
      id(newId);
      text(newText);
}

public int id() {
   return id;
}

public void id(int e) throws IllegalArgumentException {      
   if (e <= 0) {
      throw new IllegalArgumentException();
   }
   else {
      id = e;
   }
}

public String text() {
   return text;
}

public void text(String aText) throws IllegalArgumentException {
   if (aText == null || aText.length() == 0) {
      throw new IllegalArgumentException();
   }
   else {
      text = aText;
   }
}

@Override
public String toString() {
   return '"' + id() + " - " + text() + '"';
}
Run Code Online (Sandbox Code Playgroud)

然后在子类中我有这个:

public class DatedFile extends File {
private LocalDate date;

public DatedFile (int newId, LocalDate newDate, String newText) throws IllegalArgumentException {
   super(newId, newText);
   date(newDate);
}

public LocalDate date() {
   return date;
}

public void date(LocalDate aDate) throws IllegalArgumentException {
   if (aDate == null) {
      throw new IllegalArgumentException();
   }
   else {
      date = aDate;
   }
}
@Override
public String toString() {
   return '"' + id() + " - " + date + " - " + text() + '"';
}
Run Code Online (Sandbox Code Playgroud)

我是这样测试的:

public static void main(String[] args) {
   LocalDate when = LocalDate.of(2020, 1, 1);
   DatedFile datedFile1 = new DatedFile(999, when, "Insert text here");
   System.out.println(datedFile1);
Run Code Online (Sandbox Code Playgroud)

它打印:“1033 - 2020-01-01 - 在此处插入文本”但是,如果我使用以下代码

System.out.println(datedFile1.id());
Run Code Online (Sandbox Code Playgroud)

它打印正确的 id (999)。所以我认为 toString 的某些东西把它搞砸了,但我不知道问题出在哪里。

附注。我是初学者,如果我包含了太多代码,我很抱歉,但由于我不知道是什么问题,我真的不知道什么是相关的,什么不是。

Joh*_*uhn 11

你的问题在这里:

return '"' + id() + " - " + date + " - " + text() + '"';
Run Code Online (Sandbox Code Playgroud)

id()返回 an int, 和'"'is a char,这是一个数字类型。那么'"' + 9991033不是"999

要解决此问题,请使用字符串而不是字符:

return "\"" + id() + " - " + date + " - " + text() + "\"";
Run Code Online (Sandbox Code Playgroud)