1

I have overriden the method toString() in class Person, but i cant use it in my main method - "Cannot make a static reference to non-static method toString() from the type Object"

class Person {
private String name;
private int id;

public Person(String name,int id) {
    this.name = name;
    this.id = id;
}


@Override
public String toString() {
    String result = "Name: "+this.name+" ID: "+this.id;
    return result;
   }
}

public class Testing {
public static void main(String[] args) {


    Person person = new Person("Ivan",1212);
    System.out.println(toString()); // Cannot make a static reference to non-static method 

   }
}

How can i fix this ?

2
  • omg.... sorry fot the stupid question... Commented Nov 17, 2013 at 12:40
  • 3
    Paste the title of your question in google, and read one of the hundreds of returned pages. Commented Nov 17, 2013 at 12:41

4 Answers 4

2

Use:

System.out.println(person.toString());

toString method is a non-static method, meaning it is related to a specific instance.

When you want to call it, you need to call it on a specific Person instance.

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

Comments

0

You're trying to call a non-static method from a static context (in this case, your main method). To call the Person object's toString method, you'll need to do person.toString().

Sometimes thinking of our code as English helps us make sense of it. The English for this statement is "Convert the person to a string.". Let's turn this into code.

Person maps to the person object we've created. "to a string" maps to the toString() method. Objects and verbs (methods) are separated by periods in Java. The complete code for the English above is person.toString().

Comments

0

You can't call the method like that, you should use the referece "person" !

System.out.println(person.toString());

2 Comments

No need to call toString() here
Yes you're right, but i put it because I don't like to confuse user2976091
0

toString(....) is a member method of the Person Class. That means you can invoke it via an object instance of the class. So, you need to invoke person.toString() instead of toString() in System.out.println(....);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.