Search code examples
javamethodsstaticinstancenon-static

Does it make sense to have a non static method which does not use an instance variable?


The compiler does not let a static method call a non static method. I understand it does this because a not static method usually ends up using an instance variable.

But does it make sense to have a non static method which does not use an instance variable. If we have a behavior which does not affect or isn't affected by the instance state , shouldn't such a method be marked as static.


Solution

  • Often times, no. If the method doesn't touch any instance state, there's no reason to tie it to an instance.

    Of course, static methods can't be inherited or overridden, so that's one obvious time that you would want to have an instance method that doesn't use instance state. The strategy pattern is a classic example of this.

    Another case where you may tie it to an instance anyway is if this is a public API and you imagine that you may want to tie the method to instance state in the future. In that case, backwards compatibility concerns for people who are using your API may make it difficult (or impossible) to turn that static method into an instance method.