Home > Enterprise >  Instance vs Static Variable Java BIG CONFUSION
Instance vs Static Variable Java BIG CONFUSION

Time:10-12

I know for a fact that static variable is used for all instances of the object whereas the instance variable is used specifically for each instance.

However, what if we declare the instance variable in the beginning and dont touch it in the constructor ? It will act exactly as a static variable right ?

So why bother using both of those ? I'm so confused.

CodePudding user response:

"if we declare the instance variable"

... then it still is an instance variable even if you don't change it in the constructor. As the name says instance variables are for an instance only, i.e. each instance has its own copy which may have the same value. A static or global variable is only one copy that all instances have access to.

Let me make a real world example:

Several people (instances) are in a room and want to get the news.

Instance variables: everyone gets a newspaper and may chose to read it at their own pace or not at all.

Static variable: a TV in the room. Everyone gets the same channel so if anyone switches the channel all others will be affected too.

... and dont touch it in the constructor

Whether you update a variable in the constructor or not doesn't make a variable an instance variable or a global one. It's how they are declared.

Note that you could have instance variables that are changed by other methods only which is perfectly fine in many designs.

Also note that you could change a global variable in a constructor too albeit that wouldn't make much sense in many cases - but there are valid cases.

CodePudding user response:

Static variables can be used without instantiating an object. You can access these without calling class constructor. Instance variables are accessed globally within the class and if you want to use them they have to be public and you must create new object by calling constructor

  • Related