Object Oriented Programming is all about classes and objects. We first create a class in which we specify two things:
- data (variables). We use it for storing data
- behaviors (functions). We use it for manipulating/retrieving the variables.
We then create object of a class by using the
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;
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
House myHouse = new House(); int floors = myHouse.getNumberOfFloors();
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.
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
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?