user2976091
user2976091

Reputation: 233

Cannot make a static reference to non-static method issue

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 ?

Upvotes: 1

Views: 1332

Answers (4)

Nick Louloudakis
Nick Louloudakis

Reputation: 6015

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

Upvotes: 0

BilalDja
BilalDja

Reputation: 1092

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

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

Upvotes: 0

Zach Latta
Zach Latta

Reputation: 3341

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().

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19304

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.

Upvotes: 2

Related Questions