문제

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...?

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top