Java static

Static variable

public class TryNonStatic {
    int x = 0;
    TryNonStatic() {
        x ++;
        System.out.println(x);
    }

    public static void main(String[] args) {
        TryNonStatic t1 = new TryNonStatic();
        TryNonStatic t2 = new TryNonStatic();
        t2.x += 1;
        TryNonStatic t3 = new TryNonStatic();
    }
}
1
1
1

In this above example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.

public class TryStatic {
    static int x = 0;
    TryStatic() {
        x ++;
        System.out.println(x);
    }

    public static void main(String[] args) {
        TryStatic t1 = new TryStatic();
        TryStatic t2 = new TryStatic();
        t2.x += 1;
        TryStatic t3 = new TryStatic();
    }
}

1
2
4

Static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.

Static method

If you apply static keyword with any method, it is known as static method.

  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.

There are two main restrictions for the static method. They are:

  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.

Static block

  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.
public class TryStaticBlock {
    static {
        System.out.println("This is a static block.");
    }

    public static void main(String[] args) {
        System.out.println("This is a main method.");
    }
}
This is a static block.
This is a main method.

你可能感兴趣的:(Java static)