-3

Im kind of new to java and im struggling very hard at this one. I just want to make a syso with the age and name of Stefan

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

    }

What am i doing wrong?

Would be very grateful to get help

4
  • You have to add the @override annotation to toString method to overwrite it. System.out.println will call automatically the toString method. Commented Jan 22, 2018 at 18:47
  • @ChW The @Override tag only produces an error when the method doesn't actually overrides a method, it's not necessary but very useful. Commented Jan 22, 2018 at 18:50
  • 1
    Move the instantiation of Person into the main method. Commented Jan 22, 2018 at 18:52
  • The toString() of Person would create an awful StackOverflowError because it's a recursive method. Change it to public String toString(){ return "test "+alter+" "+placeofbirth;}. Also the Person stefan isn't in the scope of the main method. Commented Jan 22, 2018 at 18:57

1 Answer 1

-4

just you need write return "test" + placeofbirth ; insdead of : return "test" + stefan;`

Sign up to request clarification or add additional context in comments.

3 Comments

Nope, println(Object) automatically calls toString()
Yes sorry my bad i dont see he call recursively the function toString
Well your answer moves into the right direction.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.