+ 1

What actually static means?

can anyone describe about static keyword with real world example

22nd Jul 2017, 1:29 PM
IamSahil
IamSahil - avatar
4 Answers
+ 14
Moreover, if you were really wanting a real world example, don't forget to go through the content posted in this link : https://howtoprogramwithjava.com/static-keyword-in-java/
22nd Jul 2017, 1:58 PM
Dev
Dev - avatar
+ 3
Well, if you look at the Math class, there are many static methods. You don't want to create a new Math instance every time you use for example the pow() function. If a method or variable is static, it belongs to the class and not to an object. For example, if there's a method incrementBy(int x) which is called in the constructor of the class which contains that method with the argument 2 and the static variable y = 0, and you create three objects of that class, y will be 6. If a variable isn't static, you call it using instanceName.variable while a static one is called by this.variable or className.variable.
22nd Jul 2017, 1:55 PM
Jonas Schröter
Jonas Schröter - avatar
+ 2
Hm.. real world example. Lets answer this question: How do I know if I want to make a global variable static? From this answer you will find what static does. Lets say I want to create a Person. What does each Person have? Well, Everyone has eyes! (Hopefully) Everyone has an eyecolor! So, lets say I have an int called numEyes; This is in the Person class. Does everyone (generally) have 2 eyes???!! Yes! So, I can make it static. Now, since that's bound to the class that means every Person that is born will have 2 eyes. static int numEyes = 2; Does everyone have the same eyecolor? No! Mine are brown, his are blue! Color eyeColor; Person(Color eyeColor){ this.eyeColor = eyeColor; } This will NOT be static. That way each Person can have their own eyeColor! So, If I want the global variables to be the same throughout all object instances, I can make it static. This is however only one reason. You could also make something static because you don't want to create an object to access it too. (Which is what @Jonas touched on)
22nd Jul 2017, 4:18 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Lets say I have a Duck class and I want to create a bunch of Ducks. Also I want to keep track of the number of Ducks I have. I use a static variable to do so. (For Ducks, you can also read Cars in a garage, Students in a class, etc)
22nd Jul 2017, 7:36 PM
marit vandijk