static variable initialization java

后端 未结 2 1378
孤独总比滥情好
孤独总比滥情好 2020-12-14 00:26

how to initialize a private static member of a class in java.

trying the following:

public class A {
   private static B b = null;
   public A() {
           


        
相关标签:
2条回答
  • 2020-12-14 01:02

    Your code should work. Are you sure you are posting your exact code?


    You could also initialize it more directly :

        public class A {
    
          private static B b = new B();
    
          A() {
          }
    
          void f1() {
            b.func();
          }
        }
    
    0 讨论(0)
  • 2020-12-14 01:09

    The preferred ways to initialize static members are either (as mentioned before)

    private static final B a = new B(); // consider making it final too
    

    or for more complex initialization code you could use a static initializer block:

    private static final B a;
    
    static {
      a = new B();
    }
    
    0 讨论(0)
提交回复
热议问题