This is important to understand that when to use static method and when to use instance method:
Thumb rule for Static and Non Static is:
Use Static Method when your method is independent of state of the instance object.
Use Non Static when your method is depending upon state of the instance object.
Let’s understand this by example that is good for all of us:
public class MrHappyObject {
private String _mood = _HAPPY;
private final static String _HAPPY = "happy";
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
First we will look when to use non static method.
In above example we have 2 object obj1, obj2.
Both are born happy.
Now we call receiveHug() by obj1, and receivePinch() by obj2.Both receiveHug() and receivePinch() are non static method and they depends upon state of the object.
So the final output is:
I am happy
I am happy
I am happy
I am annoyed
That is what we want as Hugging the MrHappyObject`s Object make him happy and
Pinching it make it annoyed. We got the desired result because receiveHug(), and receivePinch() are depend upon state of object and they are non static Method.
Now Comple and run same class by making receiveHug(), and receivePinch() method Static .
public class MrHappyObject {
private final static String _HAPPY = "happy";
private static String _mood = _HAPPY;
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public static void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public static void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
And the output is
I am happy
I am happy
I am annoyed
I am annoyed
This is not our desired result.
Now this makes clear when to use Static method and when to use non static method.