+ 2

Does anybody know how to better explain what static means/does

20th Nov 2017, 9:43 AM
Cooki10
Cooki10 - avatar
3 Answers
+ 9
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it. public class Gawen { public static void doStuff(){ // does stuff } } So, instead of creating an instance of Gawen and then calling doStuff like this: Gawen f = new Gawen(); f.doStuff(); You just call the method directly against the class, like so: Gawen.doStuff();
20th Nov 2017, 9:53 AM
GAWEN STEASY
GAWEN STEASY - avatar
0
There will be times when you will want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: • They can only directly call other static methods. • They can only directly access static data. • They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in the next chapter.) If you need to do computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.
20th Nov 2017, 10:20 AM
Wasula Benjamin
Wasula Benjamin - avatar
0
gawen told you true, but this is not everything what must be said. static variable means, that there is only 1 variable for whole class. what that means? lets compare it with non static variable. lets say you create diffrent objects of the same class, and modify the variable value. if that variable is static, every change in diffrents object, will change its value, because there ia only 1 variable for whole class. if the variable is non static, every object will have diffrent variable just for this object, and values will be diffrent.
20th Nov 2017, 10:25 AM
Bartek Nowacki
Bartek Nowacki - avatar