Java - Static keyword in Java

转载 2015年07月10日 11:28:16

Sometimes I can't open this page without proper proxy configuration, so I have to copy the content here.

10 points about static keyword in Java

1) static keyword can be applied with variable, method or nested class. static keyword can not be applied on top level class. Making a top level class static in Java will result in compile time error.

2) static variables are associated with class instead of object.

3) static variables in java keeps same value for every single object.

4) you can not use non-static variable inside a static method , it will result in compilation error.

5) Static variables are bonded using static binding at compile time so they are comparatively faster than their non-static counter part which were bonded during runtime.

6) Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialized when you create instance of a particular class.

7) Static keyword can also be used to create static block in Java which holds piece of code to executed when class is loaded in Java. This is also known as static initialize block as shown in below example.

static {
        String category = "electronic trading system";
        System.out.println("example of static block in java");


Beware that if your static initialize block throws Exception then you may get java.lang.NoClassDefFoundError when you try to access the class which failed to load.

8) Static method can not be overridden in Java as they belong to class and not to object. so if you have same static  method in subclass and super class , method will be invoked based on declared type of object. For example:

public class TradingSystem {

    public static void main(String[] args) {
        TradingSystem system = new DirectMarketAccess();
        DirectMarketAccess dma = new DirectMarketAccess();
        // static method of super class will be called,
        // even though object is of sub-class DirectMarketAccess
        //static method of sub class will be called
    public static void printCategory(){
        System.out.println("inside super class static method");
class DirectMarketAccess extends TradingSystem{
    public static void printCategory(){
        System.out.println("inside sub class static method");

inside super class static method
inside sub class static method

This shows that static method can not be overridden in Java and concept of method overloading doesn't apply to static methods. Instead declaring same static method on Child class is known as method hiding in Java.

9)  If you try to override a static method with a non-static method in sub class you will get compilation error.

10)  Be careful while using static keyword in multi-threading or concurrent programming because most of the issue arise of concurrently modifying a static variable by different threads resulting in working with stale or incorrect value if not properly synchronized. most common issue is race condition which occurs due to poor synchronization or no synchronization of static variable.

Best practices - static variable and static method in Java

1)  Consider making a static variable final in Java to make it constant and avoid changing it from anywhere in the code. Also remember that if  you change value of static final variable in Java like in enum String pattern, you need to recompile all classes which use those variable, because static final variables are cached on client side.

2)  Do not use static and non static synchronized method to protect a shared resource because these two methods locked on different object, which means they can be executed concurrently.

public class SynchornizationMistakes {
    private static int count = 0;
    //locking on "this" object lock
    public synchronized int getCount(){
        return count;
    //locking on "SynchornizationMistakes.class" object lock
    public static synchronized void increment(){
Here shared count is not accessed in mutual exclusive fashion which may result in passing incorrect count to caller of getCount() while another thread is incrementing count using static increment() method.

When to make a method static in Java

1)  Method doesn't depends on object's state, in other words doesn't depend on any member variable and everything they need is passes as parameter to them.
2)  Method belongs to class naturally can be made static in Java.
3) Utility methods are good candidate of making static in Java because then they can directly be accessed using class name without even creating any instance. Classic example is java.lang.Math
4)  In various designs pattern which need a global access e.g. Singleton pattern, Factory Pattern.

Disadvantage of static method in Java

There are certain disadvantages also if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

What is nested static class in Java

Nested static class in Java is a static member of any top level class. Though you can make any class static in Java, but you can only make nested classes i.e. class inside another class as static, you can not make any top level class static. Those classes are called nested static classes.

Since to create instance of any nested class you require instance of outer class but that is not required in case of static nested class in Java. You can have an instance of nested static class without any instance of outer class. Here is an example of static nested class in Java:

public class StaticClass{

    public static void main(String args[]){
        StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
    static class NestedStaticClass{
        public String NestedStaticDescription =" Example of Nested Static Class in Java";
        public String getDescription(){
            return NestedStaticDescription;

Example of Nested Static Class in Java

When to use nested static class in Java

Normally we make a class static in Java when we want a single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask  "when to use Singleton vs Static Class in Java" for those purpose, answer is that if it's completely stateless and it work on provided data then you can go for static class otherwise Singleton pattern is a better choice.

Example of static class and method in Java library

Static method in Java is very popular to implement Factory design pattern. JDK itself is a good example of  several static factory methods like String.valueOf(). Another popular example of static method is main method in Java.

1) java.util.Collections has some static utility method which operates on provided collection.
2) java.lang.Math class has static method for maths operations.
3) BorderFactory has static method to control creation of object.
4) Singleton Classes like java.lang.Runtime.


关于static和非static变量的区别。 1. static 修饰的变量称为类变量或全局变量或成员变量,在类被加载的时候成员变量即被初始化,与类关联,只要类存在,static变量就存在。非sta...
  • a907691592
  • a907691592
  • 2016年06月14日 08:20
  • 2602


原文地址:     感谢原作者! static{}(即static块),会...
  • newjerryj
  • newjerryj
  • 2013年03月08日 13:15
  • 60298


  • fengyuzhengfan
  • fengyuzhengfan
  • 2014年07月24日 13:13
  • 9125


static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法,也可以形成静态static代码块,但是Java语言中没有全局变量的概念。  被static修饰的成员变量和成员方法独立于该类的...
  • u010931123
  • u010931123
  • 2017年03月07日 17:49
  • 553


  • zhangxiaomin1992
  • zhangxiaomin1992
  • 2016年03月30日 15:40
  • 1664

java中 static 的执行顺序问题

关于static的 父类和子类的执行顺序问题: 首先用代码来证明: 父类如下: public class staticDemo { static { int x=5; System.out.prin...
  • HGodsun
  • HGodsun
  • 2017年03月05日 13:10
  • 543


  • jsqfengbao
  • jsqfengbao
  • 2015年03月29日 08:45
  • 16434

重新认识java(六) ---- java中的另类:static关键字(附代码块知识)

  • qq_31655965
  • qq_31655965
  • 2017年01月28日 20:55
  • 3430

Java 关键字static详解

一、static基本描述对于关键字static ,大家应该不会陌生,因为一直编写: public static void main(String args[]) {...}那static表示什么呢?...
  • wei_zhi
  • wei_zhi
  • 2016年10月09日 15:57
  • 731

Java static内部类疑惑

转自:用static关键字修饰类  Java里面static一般用来修饰成员变量或函数。但有一种特殊用法是用static修饰内部类,普通类是不允许声明为静态的,只有内部类才可以。被sta...
  • u013427969
  • u013427969
  • 2016年05月28日 08:55
  • 1628
您举报文章:Java - Static keyword in Java