BLuFeNiX
BLuFeNiX

Reputation: 2594

Benefit to making objects static, even though they don't need to be?

I have many programs that declare objects at the top my class. This object will only be modified from within its own class, and there will never be more than one instance of this class running at the same time. Is there any benefit to declaring the objects as static?

public class MyClass {

    private Map<String, Object> myMap; // any reason to make this static?

    // constructor and other code here
}

Upvotes: 4

Views: 1035

Answers (3)

Stephen C
Stephen C

Reputation: 718708

Is there any benefit to declaring the objects as static?

Not really, no.

Certainly, there is no performance benefit. This is because statics are actually stored in (hidden) static frame objects that live in the heap. Ultimately, the JIT will generate native code for fetching a static variable that is no faster than an object variable fetch.


You could argue that it is more convenient to use a static to share some data structure "globally" within an application. But that convenience has some significant disadvantages. The biggest ones are that statics make testing harder, and they make code reuse harder.


However, you shouldn't confuse the general case with the specific case where the static holds or refers to an immutable value or data structure; e.g. like a String constant or a constant mapping. These can be justified on both design and practical grounds; e.g.

  public static final String THE_ANSWER = "Forty two";

  private static final Map<String, Integer> SCORES;
  static {
      Map<String, Integer> map = new HashMap<>();
      tmp.put("perfect", 100);
      tmp.put("average", 50);
      tmp.put("fail", 20);
      SCORE = Collections.unmodifiableMap(map);
  }

This is fine ... so long as there is no possibility that different (current or future) use-cases require different values / mappings / whatever. If that is a possibility, then static could be harmful.

Upvotes: 0

drvdijk
drvdijk

Reputation: 5554

The one reason for making members static is constants. public static final Sting SOME_CONSTANT = "amazing"; is way easier to access statically than though an instance.

Reasons to not use static members is testing (how to easily mock a static member?) or (specifically with a map) thread safity.

Upvotes: 1

Moayad Al-sowayegh
Moayad Al-sowayegh

Reputation: 87

Declaring Variables as static makes the variable shared among all objects of the class ( in your example MyClass) another thing that you can make static methods that return the variable without creating an object of the class

MyClass.method();

sometimes this makes more sense than create an object of MyClass then call the Method, like the Math class one side issue: if you want to have only one instance of MyClass, checkout Singleton Design Pattern which insure only on instance of the class

Upvotes: 1

Related Questions