【发布时间】:2018-01-22 18:45:06
【问题描述】:
我是 java 的新手,我在这方面非常努力。我只想用 Stefan 的年龄和名字做一个 syso
public class Person {
public int alter;
public String placeofbirth;
public Person(int alter, String placeofbirth) {
this.alter = alter;
this.placeofbirth = placeofbirth;
}
Person stefan = new Person(19, "Berlin");
public String toString() {
return "test" + stefan;
}
public static void main(String[] args) {
System.out.println(stefan);
}
}
我做错了什么?
非常感谢您的帮助
【问题讨论】:
-
您必须在 toString 方法中添加 @override 注解才能覆盖它。 System.out.println 会自动调用 toString 方法。
-
@ChW
@Override标签仅在方法实际上没有覆盖方法时才会产生错误,这不是必需的,但非常有用。 -
将
Person的实例化移动到main方法中。 -
Person的toString()会创建一个糟糕的StackOverflowError,因为它是一种递归方法。将其更改为public String toString(){ return "test "+alter+" "+placeofbirth;}。此外,Personstefan不在 main 方法的范围内。