+ 2

Can anyone explain me the static methods and static variable in java?

30th Nov 2016, 3:02 PM
PRAVALLIKA.K
PRAVALLIKA.K - avatar
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.
30th Nov 2016, 9:25 PM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar
+ 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.
30th Nov 2016, 9:26 PM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar
+ 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.
30th Nov 2016, 7:16 PM
Arsal Ali
Arsal Ali - avatar