Books / Ruby for Beginners / Chapter 31
People think that Object-Oriented Programming is something very complicated, magical and not easy to tackle. But in reality it’s all pretty straightforward if we talk about things you gonna be working on daily. The right way of doing OOP could simplify the daily life of a programmer. However, it requires more brain power than the common way of doing OOP.
This books covers the essentials, common way of doing OOP, which is a must for every beginner. If you’re looking for an elegant way of writing your object-oriented code, start reading “Elegant Objects” by Egor Bugayenko.
Classes and objects
“Object-Oriented Programming” assumes there should be an object somewhere. But what are objects? From our everyday lives we know that everything is an object. Book on the table, for example. A man walking down the street. BMW model E34 crossing the road. But if you look closer, BMW E34 is a certain class of objects. With all the variety of other cars, this particular one is exactly the same as another of the same model. But at the same time they’re different instances.
The most obvious example of a class is a technical drawing (model) of some product:
You can see technical details of a product like width, height, radius, and so on. You can see these details before the final product is actually manufactured. Class in programming language is something similar to this drawing. It’s a pattern, and based on this pattern we can create something real:
And something real is the actual object (or multiple objects) we’re building based on this drawing. Objects are also known as instances or class instances.
Having one drawing we can create multiple objects, and the same is true for a class. There is one class, and multiple objects you can create based on this class. For example:
class Car end car1 = Car.new car2 = Car.new car3 = Car.new
Above we have only class, and three objects: three cars created with this drawing. Our “drawing” takes only two lines, but it’s only because or drawing is default (empty). There is nothing super special in our class at the moment, but in real life we normally add some characteristics to cars (like color, audio options, license plate number and so on).