Pregunta

Sup guys, I have a simple, but bugging question. As far as I understand, static basically means, that for every single instance of that class, this method will be the same, if we change it, this will change for every single instance of that class, it's also known as Class Method. Well, if I have a class that implements toString () method witch a certain format, let's say:

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

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

¿Fue útil?

Solución

This does not apply only to toString()

The Java Language Specification says

It is a compile-time error if a static method hides an instance method.

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

From an Object Oriented point of view, see the other answers to this question or related questions.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top