Advantages and Disadvantages of using Static in JAVA

Advantages:

Static members/methods are used as in helper classes say like Math or in constants classes. which helps other objects to utilize Strings or useful functions for which you do not need to create object but invoked using Class name.
Example – singleton objects are invoked using a static function.

Disadvantages:

Static members are part of class and thus remain in memory till application terminates and can’t be ever garbage collected. Using excess of static members sometime predicts that you fail to design your product and trying to cop of with static / procedural programming. It denotes that object oriented design is compromised. This can result in memory over flow.
Also there are certain disadvantages if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

Things to remember:

The static variable will be part of the class definition rather than on the heap. However static variables are useful when you know there will be accesses to the object from multiple places. Access to static resources is not thread safe. You might get weird/unpredictable results in a threaded environment. But if your only reading the static value then using threads for it is fine.

How Static Breaks encapsulation:

The technical implementation of them is to allow state to be maintained across all instances of a class. The problem is that this is intrinsically not OOP because it disregards encapsulation. If a variable can be altered by any instance of a class then the fundamental principle behind encapsulation/information hiding is lost entirely: An object is no longer in complete control of its state. Its state now relies on variables which are essentially global. Which we know is bad. Even private static variables maintain state at a global level but simply limit its access. Any instance of the object can alter the static variable which causes ambiguity as individual instances of the object no longer have control over their own state. State changes can arbitrarily happen without knowledge of an object which relies on that state which is problematic because the object may not work correctly when this happens. Much as it’s often said that “Inheritance breaks encapsulation” statics do this in a far more severe way: By not just exposing internal implementation but also by exposing internal state.

Gopal Das
Follow me

1 Comment

  1. What about the case when there is a class having methods only and no variables and those methods are going to be called very frequently throughout the lifetime of jvm.

Leave a Reply

Your email address will not be published. Required fields are marked *