javamethodsmodifiers

Why aren't all Java methods static?


I am just checking my reasoning here, because I think I already know the answer. Someone asked me: No matter how many instances I might have of a particular class, a given method will surely have the same operation in each of those objects. So why have Java developers invented the static modifier for methods? We can contrast this with static variables. Here, of course, each object can have a different value for a given field.

My response was that, no, a given method will not have the same operation in each instance of the class. For example, setters and getters operate in "identical" ways in each instance of a class, but their output does depend on the instance of the class.


Solution

  • Pretty broad question; but there are various simple facts to put up here: as static is regarded an abnormality regarding "good OO" principles:

    In other words: you strive to not use static by default. There are cases where it makes sense; but you have to carefully consider those.

    Or, giving my personal two cent: if static would be the "better answer", everybody would still be coding in Pascal and claim that imperative programming is the silver bullet of software engineering.

    But to answer the "other" question here: "why do we need static at all then"?

    Simply because it is convenient and helpful sometimes. When you turn to the java "system classes"; such as Collections or Objects you find a reasonable amount of "helpful" functionality there. And that allows to uphold other important properties of software quality; like: single responsibility principle. It makes sense that there is one central implementation of sort() for example; instead of having an "additiony" "can be sorted" behavior on collections directly.