When writing a computer program, there are different approaches we can follow to solve a specific problem. Some people can focus on solving it by creating subprograms or functions to solve each small part of the problem (Structured programming paradigm). In an Object-Oriented Programming (OOP) style, on the other hand, the main focus is to create a model of each one of the actors (objects) involved in the problem, modeling both their attributes and behaviors.
The main concept around this OOP programming paradigm is the object. An object could be described as a sort of entity that has some attributes (state of the object) and can execute some tasks (behavior of the object).
For example, an object called Student can have some attributes: name, weight, height, age, etc. and its own behaviors: learn, talk, sleep (during a class), etc. Any “real world” concept can be modeled as an object.
Attributes belong to the object and are specific for each. For example, if we have a car object we can define some attributes and behaviors for it:
But we can be dealing with more than one car in our problem, if we define multiple cars each one of them could have a totally different set of values assigned to their attributes:
Both are objects, both cars, but the values assigned to each attribute are different for the two cars and, if some behaviors are based on these values, the result obtained for each would also be different:
The OOP programming approach starts by identifying the objects involved in a problem, its attributes and behaviors, and writing down this in a general model called class.
Usually, when starting a project to construct a building, the first step to be taken is to draw its design in a blueprint, in which we are going to define the main features the building would have. Then, based on this design we can build one or multiple buildings
A class is a blueprint for a specific type of objects, all the objects created from the same class would share the structure defined in it, but would have different states:
As with blueprints, by itself classes are not going to do anything. We can not live, work, or enter into a blueprint, for this to be possible we still need to construct the actual buildings. The same is true for classes, we need to construct objects based on them in order to be able to use the defined features and behaviors. Each object we created will be an instance of the class we designed, following its structure.
When we write our classes in a programming language (Java, C#, Python, etc) we define the attributes as class-level variables, and the behaviors as methods (subprograms) inside the class structure:
- The OOP paradigm focus on identifying the objects involved in a problem and creating a model for them
- Classes are blueprints that define the structure a type of objects will follow (attributes and behaviors)
- Objects are instances of classes
- Each object will have its own state (defined by attributes) and behaviors