1Static keyword is used a lot in java.
2 Static means, you
3can access those static variables
4without creating an object,
5just by using a class name.
6This means that only one instance of
7that static member is created which
8is shared across all instances of the class.
9Basically we use static keyword when
10all members share same instance.
1static keyword is a non-access modifier. static keyword can be used with
2class level variable, block, method and inner class or nested class.
1We can declare a method as static by adding keyword “static” before method name.
2Let’s see example on static method in java.
3
4public class StaticMethodExample
5{
6 static void print()
7 {
8 System.out.println("in static method.");
9 }
10 public static void main(String[] args)
11 {
12 StaticMethodExample.print();
13 }
14}
1class JavaExample{
2 private static String str = "BeginnersBook";
3
4 //Static class
5 static class MyNestedClass{
6 //non-static method
7 public void disp() {
8
9 /* If you make the str variable of outer class
10 * non-static then you will get compilation error
11 * because: a nested static class cannot access non-
12 * static members of the outer class.
13 */
14 System.out.println(str);
15 }
16
17 }
18 public static void main(String args[])
19 {
20 /* To create instance of nested class we didn't need the outer
21 * class instance but for a regular nested class you would need
22 * to create an instance of outer class first
23 */
24 JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
25 obj.disp();
26 }
27}