DEV Community

Muhammad Wasi Naseer
Muhammad Wasi Naseer

Posted on

What is static and non-static in OOP?

Object Oriented Programming is all about classes and objects. We first create a class in which we specify two things:

  1. data (variables). We use it for storing data
  2. behaviors (functions). We use it for manipulating/retrieving the variables.

We then create object of a class by using the new keyword.

The variables or behaviors can either be accessed at class level or object level.
The class level access means that we can directly access them using the class name. For example:


 int maxRoomInHouse = House.MAX_ROOMS;

Enter fullscreen mode Exit fullscreen mode

The object level means that we can only access them using the object of the class. The object level access is the default access of variables or functions unless we specify static.


House myHouse = new House();
int floors = myHouse.getNumberOfFloors();

Enter fullscreen mode Exit fullscreen mode

We can make a function or variable to be accessed at class level by specifying static. We don't need to create an object to access static variables or functions.

When to use static and non-static?

We should use static variables or functions wherever we need global common variable or behavior across all the objects of the class. For example, in our house example, the House.MAX_FLOORS is the common field that we will be same for all objects of the House class, and same goes for House.getMaxFloors() function.

We should not specify variable or function static whenever the function or variables belongs to each individual object. For example, in myHouse.getNumberOfFloors() is basically specifying how many floors does myHouse object has?

Discussion (0)