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

问题描述 投票:1回答:2

我有一个抽象超类,它具有两个属性:int和string。我已经覆盖了toString方法及其具有一个额外属性(LocalDate)的子类中的方法。但是,由于某些我不了解的原因,当我将子类打印到Sring info时,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() + '"';
}

然后在子类中,我有这个:

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() + '"';
}

我这样测试:

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);

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

System.out.println(datedFile1.id());

它会打印正确的ID(999)。因此,我假设使用toString的东西将其弄乱了,但我不知道问题出在哪里。

PS。我是一个初学者,很抱歉,如果我包含过多的代码,但是由于我不知道问题出在哪里,我真的不知道什么是相关的,什么不是。

java overriding subclass tostring superclass
2个回答
7
投票

您的问题在这里:

return '"' + id() + " - " + date + " - " + text() + '"';

id()返回int,并且'"'char,这是数字类型。因此,'"' + 9991033,而不是"999

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

return "\"" + id() + " - " + date + " - " + text() + "\"";

1
投票

toString()的方法从'"'更改为" \""

'"'是一个字符(内部存储为Integer),因此将其与id()相加会产生您看到的结果。

© www.soinside.com 2019 - 2024. All rights reserved.