DEV Community

Cover image for #4 Known is a drop! Class Variables -Static Variable and Instance variable
Deepikandas
Deepikandas

Posted on

#4 Known is a drop! Class Variables -Static Variable and Instance variable

A class can have two types of variable:
1.Static Variable
2.Instance Variable

STATIC VARIABLE:

  • Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

  • Fields that have the static modifier in their declaration are called static fields or class variables.

  • Every instance of the class shares a class variable, which is in one fixed location in memory.
    Static (class-level) variables can be manipulated directly using the class name, without instantiating the class.

  • Static variables can be accessed with class name.

  • Static variables can be used both in static methods and non static methods without using object reference.

  • Value assigned to static variable can be changed anytime, at any part of the program.


Instance Variables:

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword.

  • Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words);

  • Non static variables/instance variables can be used in non static method directly(no need of object reference),whereas while using instance variables in static methods,object ref is needed.

Top comments (0)