- Static keyword can be applied to instance variable, instance method and inner classes.
- There is only one copy of static variable and all objects share them.
- Static variables are loaded and initialized when the class is loaded.
- Static variable are also called as static fields, class variables.
- Static applied with final becomes constant field. The naming convention of a constant is all uppercase and more than one word separated by underscore (_)
- Static method cannot access non-static (instance) methods.
- Static method cannot access non-static (instance) variables.
- Static method can only access static methods and variables.
- A common use of static methods is to access static fields
- Static method cannot use this or super keyword in any way.
- Sub class will not inherit super-class’s static members.
- If you wish to access a static member (method/variable) from outside its class, you can do so using dot operator on class name.
class StaticDemo { static int a=0; int b=++a; static int c=++a; public static void main(String[] args){ System.out.print(c); } }
The output of the above code would be 1. When the class is loaded, variable ‘a’ would be initialized to 0 and the value is incremented and stored in variable ‘c’.
public static final double PI = 3.14;
package com.ibytecode.keywords.staticdemo; public class Student { private String name; int id; public static void main(String[] args) { System.out.println("Number of Students created: " + id);//ERROR } }
className.method( )
or
className.variable
When we give the command ,
java Hello
to run our program, JVM calls Hello.main() to start our program execution. main() is declared static because otherwise JVM will not be able to instantiate the class due to ambiguity in calling and passing arguments to the constructor and that’s the reason main() method has static in its method signature.