Why can't toString () be a static method?

Guys, I have a simple but incomprehensible question. As far as I understand, static basically means that for every single instance of this class this method will be the same if we change it, it will change for every single instance of this class, also known as a class method, Well, if I have a class, which implements the toString () method with a specific format, say:

 public String toString() { return "(" + x + "," + y + ")"; } 

Why can't it be set as static? Since this format will be the same for every instance of this class ...?

+6
source share
2 answers

This does not apply only to toString()

Java language specification says

This is a compile-time error if the static method hides an instance of the Method.

Since the toString() instance method is implicitly inherited from Object , declaring the toString() method as static in the subtype causes a compile-time error.

From an object-oriented point of view, see other answers to this question or related questions .

+8
source

Because the static method cannot access instance fields. In addition, java.lang.Object is specified toString() , so you must have an Object instance to call toString() on. Finally, if toString() was static, it would have to accept Object instances (how else could you call toString () on an n instance of a class?).

+4
source

All Articles