What is the exact meaning of static fields in Java?

后端 未结 4 1002
迷失自我
迷失自我 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:52

    What you are looking for is called the Singleton Pattern.

    0 讨论(0)
  • 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());
    
    0 讨论(0)
  • 2020-11-22 14:57

    Static doesn't quite mean "shared by all instances" - it means "not related to a particular instance at all". In other words, you could get at the static field in class A without ever creating any instances.

    As for running two programs within the same JVM - it really depends on exactly what you mean by "running two programs". The static field is effectively associated with the class object, which is in turn associated with a classloader. So if these two programs use separate classloader instances, you'll have two independent static variables. If they both use the same classloader, then there'll only be one so they'll see each other's changes.

    As for an alternative - there are various options. One is to pass the reference to the "shared" object to the constructor of each object you create which needs it. It will then need to store that reference for later. This can be a bit of a pain and suck up a bit more memory than a static approach, but it does make for easy testability.

    0 讨论(0)
  • 2020-11-22 15:09

    Static methods and members are discouraged because they're so frequently misused, but this sounds like a situation where static is the correct way to go. As to static shared across multiple programs, this is not the case. Each program runs in a completely separate environment.

    0 讨论(0)
提交回复
热议问题