Java

Java static

2018-01-05  本文已影响1人  JaedenKil

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();
        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.

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

Static block

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.
上一篇 下一篇

猜你喜欢

热点阅读