在构造函数中初始化静态最终字段

发布于 2024-10-19 00:56:14 字数 262 浏览 2 评论 0原文

public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final 表示该变量只能分配一次(在构造函数中)。
  • static 意味着它是一个类实例。

我不明白为什么这会被禁止。这些关键词在哪里互相干扰?

public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final means the variable can only be assigned once (in the constructor).
  • static means it's a class instance.

I can't see why this is prohibited. Where do those keywords interfere with each other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

楠木可依 2024-10-26 00:56:15

Static

关键字static 表示对象的成员(在本例中为字段)不依赖于类的实例,而是一般类的成员。如果静态成员是一个字段,则它会在类加载期间初始化。

它可以通过类而不是通过实例访问(尽管后者并非不可能,但它被认为是不好的形式),因此在构造函数根本没有运行的情况下就可以访问它。

Final

当关键字final应用于对象的字段时,意味着它只能被赋值一次,并且它必须在初始化期间被赋值。

Static Final

结合起来,这两个关键字有效地定义了一个常量:它只能被赋值一次,必须被赋值,并且对于该类的所有实例都是相同的。

由于静态字段是在类加载期间初始化的,因此必须在声明时或在静态初始化块中对其进行初始化。

这意味着,如果您到达构造函数,它就已经被初始化了,因为它需要已经被初始化了。

Singleton

如果您正在寻找一个只分配一次但多次读取的类成员,那么您正在处理 一个单身人士。单例模式通常用于访问共享资源。

该字段是静态的,但不是最终的;相反,当访问该字段时,代码会检查它是否已经初始化,如果没有,则立即完成。请注意,在多线程环境中,您需要同步对该字段的访问,以避免在初始化时对其进行访问。

Static

The keyword static means that a member of an object, in this case a field, is not tied to an instance of a class, but is a member of the class in general instead. If the static member is a field, it is initialised during loading of a class.

It is accessible through the class rather than through an instance (though the latter is not impossible, it is considered bad form), so it is accessible without the constructor having ran at all — ever.

Final

The keyword final, when applied to a field of an object, means that it can be assigned to only once, and that it has to be assigned to during initialisation.

Static Final

Taken together, these two keywords effectively define a constant: it can be assigned to only once, has to be assigned to, and is the same for all instances of that class.

Since the static field is initialised during class loading, it has to be initialised then, either at declaration, or in a static initialiser block.

This means that if and when you reach the constructor, it will already have been initialised, because it needed to already have been initialised.

Singleton

If you're looking for a class member that you only assign to once, but read many times, you're dealing with a singleton. The singleton pattern is commonly used for access to a shared resource.

The field is made static but not final; instead when accessing the field, the code checks whether it has been initialised already, if not, it is done then and there. Note that in environments with multiple threads, you need to synchronise access to the field, to avoid accessing it while it is initialising.

丘比特射中我 2024-10-26 00:56:15

想一想。您可以使用代码执行此操作:

A a = new A();
A b = new A(); // Wrong... x is already initialised

初始化 x 的正确方法是:

public class A 
{    
    private static final int x = 5;
}

public class A 
{    
    private static final int x;

    static
    {
        x = 5;
    }
}

Think about it. You could do this with your code:

A a = new A();
A b = new A(); // Wrong... x is already initialised

The correct ways to initialise x are:

public class A 
{    
    private static final int x = 5;
}

or

public class A 
{    
    private static final int x;

    static
    {
        x = 5;
    }
}
南街九尾狐 2024-10-26 00:56:15

Final 并不意味着必须在构造函数中初始化。
一般来说,这样做是这样的:

 private static final int x = 5;

静态意味着变量将通过类的多个实例共享。例如 :

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

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
幸福%小乖 2024-10-26 00:56:15
    public class StaticFinalExample {
  /*
   * Static final fields should be initialized either in
   * static blocks or at the time of declaration only
   * Reason : They variables are like the utility fields which should be accessible
   * before object creation only once.
   */
  static final int x;

  /*
   * Final variables shuould be initialized either at the time of declaration or
   * in initialization block or constructor only as they are not accessible in static block
   */
  final int y;

  /*
   * Static variables can be initialized either at the time of declaration or
   * in initialization or constructor or static block. Since the default value is given to the
   * static variables by compiler, so it depends on when you need the value
   * depending on that you can initialize the variable appropriately
   * An example of this is shown below in the main method
   */
  static int z;

  static {
    x = 20; // Correct
  }
  {
    y = 40; // Correct
  }
  StaticFinalExample() {
    z = 50; // Correct
  }
  public static void main (String args[]) {
    System.out.println("Before Initialization in Constructor" + z);   // It will print 0
    System.out.println("After Initializtion in Constructor" + new StaticFinalExample().z); // It will print 50
  }
}
    public class StaticFinalExample {
  /*
   * Static final fields should be initialized either in
   * static blocks or at the time of declaration only
   * Reason : They variables are like the utility fields which should be accessible
   * before object creation only once.
   */
  static final int x;

  /*
   * Final variables shuould be initialized either at the time of declaration or
   * in initialization block or constructor only as they are not accessible in static block
   */
  final int y;

  /*
   * Static variables can be initialized either at the time of declaration or
   * in initialization or constructor or static block. Since the default value is given to the
   * static variables by compiler, so it depends on when you need the value
   * depending on that you can initialize the variable appropriately
   * An example of this is shown below in the main method
   */
  static int z;

  static {
    x = 20; // Correct
  }
  {
    y = 40; // Correct
  }
  StaticFinalExample() {
    z = 50; // Correct
  }
  public static void main (String args[]) {
    System.out.println("Before Initialization in Constructor" + z);   // It will print 0
    System.out.println("After Initializtion in Constructor" + new StaticFinalExample().z); // It will print 50
  }
}
愿与i 2024-10-26 00:56:14

每次创建类的实例时都会调用构造函数。因此,上面的代码意味着每次创建实例时都会重新初始化x的值。但是因为变量被声明为final(并且是static),所以你只能这样做

class A {    
    private static final int x;

    static {
        x = 5;
    }
}

但是,如果你删除static,你可以这样做:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

或者这样:

class A {    
    private final int x;

    {
        x = 5;
    }
}

A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

class A {    
    private static final int x;

    static {
        x = 5;
    }
}

But, if you remove static, you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

OR this:

class A {    
    private final int x;

    {
        x = 5;
    }
}
(り薆情海 2024-10-26 00:56:14

static Final 变量在类加载时初始化。构造函数可能会在很晚之后被调用,或者根本不会被调用。此外,构造函数将被多次调用(每个新对象),因此该字段不再是最终字段。

如果您需要自定义逻辑来初始化静态最终字段,请将其放入静态块中

static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.

If you need custom logic to initialize your static final field, put that in a static block

2024-10-26 00:56:14

想想第二次实例化一个对象时会发生什么。它尝试再次设置它,这是静态决赛明确禁止的。只能为整个类设置一次,不能为实例设置一次。

您应该在声明时设置该值。

private static final x=5;

如果您需要额外的逻辑或更复杂的实例化,可以在静态初始化程序块中完成。

Think about what happens the second time you instantiate an object. It tries to set it AGAIN, which is expressly prohibited by being a static final. It can only be set one time for the entire class, not instance.

You should set the value when you declare it

private static final x=5;

If you need additional logic, or more complex instantiation, this can be done in a static initializer block.

蘸点软妹酱 2024-10-26 00:56:14

static 意味着该变量在应用程序中是唯一的。
final 意味着它只能设置一次。

如果在构造函数中设置它,则允许多次设置该变量。

因此,您应该直接初始化它或提出一个静态方法来初始化它。

static means that the variable is unique on the application.
final means that it should be set only once.

If you set it in your constructor, you allow to set the variable more than once.

Hence you should intialize it directly or propose a static method to initialize it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文