What is the exact meaning of static fields in Java?

后端 未结 4 1048
迷失自我
迷失自我 2020-11-22 14:16

I would like to share an object between various instances of objects of the same class.

Conceptually, while my program is running, all the objects of class A access

4条回答
  •  無奈伤痛
    2020-11-22 14:55

    Assuming everything is in the same class loader, then why not use the monostate pattern to do this?

    Your shared static is hidden in the monostate:

    
      public class Monostate {
    
          private static String str = "Default";
    
          public String getString() {
              return str;
          }
    
          public void setString(String s) {
              str = s;
          }
      }
    
    

    Then you are free to create as many instances of the monostate as you like, but they all share the same underlying object due to the static reference.

       Monostate mono = new Monostate();
       mono.setString("Fred");
       System.out.println(mono.getString());
    

提交回复
热议问题