+ 2
Can anyone explain me the static methods and static variable in java?
3 Answers
+ 2
static method. It is aĀ methodĀ which belongs to the class and not to the object(instance) AĀ static methodĀ can access onlyĀ staticĀ data. It can not access non-staticĀ data (instance variables) AĀ static methodĀ can call only otherĀ static methodsĀ and can not call a non-static methodĀ from it.
+ 2
static variableĀ (āstaticā Keyword = ClassĀ Variables) InĀ Java VariablesĀ can be declared with the āĀ staticĀ ā keyword. Example:Ā staticĀ int y = 0; When aĀ variableĀ is declared with the keywordĀ staticĀ , its called a classĀ variableĀ . All instances share the same copy of theĀ variable.
+ 1
The difference lies in the reason why they are in a class.
Let me Give you an example:
public class Car{
int door;
int hp;
String model;
static String weather;
//additional methods and constructor aren't listed.
}
We can clearly see that weather has nothing to with cars.. Generally.
So if you use variables in a class from which you know they have nothing to do with other variables in this class, you make them static.
Also you can't access on non static variables with static methods and vice versa.