-6

I am studying about static variables. They say that static variables are class variables. They gave an example like this

class Bicycle{
    private static int noOfBicycles = 0;
} 

When calling this we can directly use the name of the class to call this variable without creating any object, i.e.

Bicycle.noOfBicycles

So when do we need these static variables rather than instance variables?

Abra
  • 19,142
  • 7
  • 29
  • 41
  • whenever you required to rid out from repeated variable then we use static variable instead because static is referred to memory management. – Kandy Mar 20 '20 at 05:20

1 Answers1

0

When a variable is declared as static, a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Instance variables are non-static variables and are declared in a class outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.

The main differences between static and non static variables are better explained here

Also already answered Static vs Instance Variables: Difference?

Community
  • 1
  • 1