gpt4 book ai didi

java - 我不明白在将 toString 与我的 UI 混合时遇到的问题

转载 作者:行者123 更新时间:2023-12-01 21:34:47 25 4
gpt4 key购买 nike

我有一个父类(super class)和两个子类。当我单击按钮时,这两个子类将在我的用户界面上使用。我想创建一个学生并将其放在一个列表中。 Estudiante 内部有很多属性,因此我在子类和父类(super class)上都有 toString 方法。我已经编辑了 setListData 的属性,因此不再需要字符串。问题是,现在当我运行程序并尝试添加一个 Estudiante 并显示它时,它在子类和父类(super class)的 toString 行上给出了 StackOverflowError 。如果有人可以尝试用我的代码修复它,我将非常感激。谢谢

我没有尝试太多,我只是改变了过去设置列表的方法,但现在理论上它是固定的。

public class Estudiante extends Persona{
private int numero;
private int semestre;

public Estudiante(String unNombre, int unaCedula, String unMail, int unNumero, int unSemestre) {
super(unNombre,unaCedula,unMail);
this.setNumero(unNumero);
this.setSemestre(unSemestre);
}

Estudiante 的 toString() (我没有发布 get 和 set 方法,因为我认为它们并不重要)

@Override

public String toString(){
return super.toString() + "Numero:" + this.getNumero() + "Semestre: " + this.getSemestre();
}
```

父类(super class) TOSTRING(女神异闻录)

@Override
public String toString(){
return toString() + "Nombre"+ this.getNombre() + "Cedula " + this.getCedula() + "Mail " + this.getMail();
}

public Persona(String unNombre, int unaCedula, String unMail){
this.setNombre(unNombre);
this.setCedula(unaCedula);
this.setMail(unMail);
}

这就是我在用户界面上的内容

private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {                                                     
Estudiante unEst=new Estudiante(NombreEstudiante.getText(), Integer.parseInt(CedulaEstudiante.getText()),MailEstudiante.getText(), Integer.parseInt(NumeroEstudiante.getText()), Integer.parseInt(SemestreEstudiante.getText()));
modelo.agregarEstudiante(unEst);
ListaEstudiantesJ.setListData(modelo.getListaEstudiantes().toArray());

子类和父类(super class)中的两个 toString 行均出现 StackOverflowError。

最佳答案

这个

public String toString(){
return toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}

调用重写的 toString:

public String toString(){
return super.toString()
+ "Numero:" + getNumero() + "Semestre: " + getSemestre();
}

它再次调用原始的 toString。

因此,无限循环。

在基类中有两种可能性:

只有 super.toString() 是正确的:

public String toString(){
return super.toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}

或者根本就没有 toString。

public String toString(){
return "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}

关于java - 我不明白在将 toString 与我的 UI 混合时遇到的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com