| Start |
|---|
| Reference to non-static member from static context Static variables and methods are not part of an instance, There will always be a single copy of that variable no matter how many objects you create of a particular class. For example you might want to have an immutable list of constants, it would be a good idea to keep it static and initialize it just once inside a static method. This would give you a significant performance gain if you are creating several instances of a particular class on a regular basis. Furthermore you can also have a static block in a class as well. You can use it to assign a default value to a static variable. They are executed only once when the class is loaded into memory. Instance variable as the name suggest are dependent on an instance of a particular object, they live to serve the whims of it. You can play around with them during a particular life cycle of an object. All the fields and methods of a class used inside a static method of that class must be static or local. If you try to use instance (non-static) variables or methods, your code will not compile. |
| Using static to declare constants As the As constants cannot change, For example, to define the mathematical constant of pi: Which can be used in any class as a constant, for example: |
| Using static with this Static gives a method or variable storage that is not allocated for each instance of the class. Rather, the static variable is shared among all class members. Incidentally, trying to treat the static variable like a member of the class instance will result in a warning: Methods that are declared static behave in much the same way, but with an additional restriction: You can't use the In general, it's best to declare generic methods that apply to different instances of a class (such as clone methods) Syntax
|
Read Article
https://develop.horje.com/learn/1434/reference