Initialize a static final field in the constructor

后端 未结 8 604
执念已碎
执念已碎 2020-11-30 22:57
public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final means the variable can
8条回答
  •  心在旅途
    2020-11-30 23:20

    Final doesn't mean that is has to be initialized in the constructor. Generally this is what is done :

     private static final int x = 5;
    

    static instead means that the variable will be shared through multiple instances of the class. For example :

    public class Car {
       static String name;
       public Car(String name) {
          this.name = name;
       }
    }
    
    ...
    
    Car a = new Car("Volkswagen");
    System.out.println(a.name); // Produces Volkswagen
    
    Car b = new Car("Mercedes");
    System.out.println(b.name); // Produces Mercedes
    System.out.println(a.name); // Produces Mercedes
    

提交回复
热议问题