+ 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 Réponses
+ 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