When we can have class and method as static?
Anybody please help me with some example...
4 Answers
You can make a method static if it doesn't use any non-static members of the class.
You can make a class static if it only contains static members.

- 6,561
- 2
- 15
- 18
If a method doesn't change it's behaviour based on different objects of it's enclosing class. it can be marked static
.
Check Math
class. all of it's methods are static
cause, their behaviour just depends on the argument within methods and those methods don't make any change in the class states.
All the utility/helper methods can be (should be) marked as static
. i.e. if their behaviour is same for all objects, why to have different copy for each object, just have one copy and let all objects share same copy.
You should check this also: Why are you not able to declare a class as static in Java?
When you don't need a class instance to invoke that method. It means that method does not depend on any non-static members of the class

- 7,782
- 2
- 24
- 31
A static method belongs to the Class and thus not to a specific instance. If you think at programming languages in term of message dispatching we can say procedural programming provides only 1 level of message dispatching as the name of the function correspond to its actual behavior. In Object Oriented Programming we have two level of message dispatching as you also has you have to specify an object plus the signature of a function (method). The same function may behave differently on different object depending on their status (subClass overridden method, etc.). A static method is instead like a global function you can execute where and how you want and always has the same behavior.
You may therefore limit the usage of static methods although there are cases in which they are helpful. In the Singleton pattern (http://it.wikipedia.org/wiki/Singleton) a static method is necessary to retrieve the Singleton's instance (also a private static attribute is necessary to keep track of it).
For those who claim Singleton are evil and you should always use Dependency Injection via Google Guice, also Guice relies on static method for instance to create an injector (http://lowcoupling.wordpress.com/2012/12/05/dependency-injection/).
So I guess the best answer is you should always think if the problem you are facing might just be solved by the injection of object but there are cases in which the usage of static methods is pretty reasonable.

- 7,358
- 6
- 47
- 84