+ 3

What are the differences between a static variable and a non - static variable (java)?

2-3 valid differences will be highly appreciated

29th Jul 2017, 10:18 AM
Danish Javed
Danish Javed - avatar
3 Respostas
+ 3
Sure. Tried to fit any extra info I could. Static: The member is bound to the class itself * Cannot be overrided As a result, Polymorphism cannot occur * Stays the same throughout all object instances * Can be called via class name * Can also be called via class instance // Extra * The Static Block will be called when the class loads static{ } Non Static: The member is bound to an instance of the class * Can be overrided Polymorphism can occur * All object instances have their own members * Must be called via class instance // Extra * The initializer block is called on object instantiation (Similar to a constructor). { }
29th Jul 2017, 2:49 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
static makes the member bound to the class itself, so something that's non-static means the member is bound to an instance of the class. For example, if I have the non-static method: void doStuff(){ } In order to call it, I must create an instance of the class. myClass obj = new myClass(); obj.doStuff(); This also means I cannot directly call a non-static method from a static method. This is due to not having a class instance in the static block. There's also some other things that happen as a result of making something bound to the class. (But that isn't exactly what static means). Such as, * You can call a static member via className, rather than object instance. * You cannot override a static member. * A static variable will be the same throughout all object instances. For example, a static variable can be used to keep track of how many objects were created in that class.
29th Jul 2017, 2:35 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
Thanks @RestoringFaith If feasible, can you write in point wise form or tabular form with their respective differences side by side
29th Jul 2017, 2:40 PM
Danish Javed
Danish Javed - avatar