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.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容