Monday, January 28, 2013

6.1. Why objects?


So far we have looked for algorithms and we have tried to turn anything into a function to use in our programs. When we know which steps we must take, we look for the variables required for such steps.

Let's suppose we have to store data about a door in a simulation program. Do we create functions OpenDoor and CloseDoor? At least, we should also go to the area of ​​variable declarations, to keep other data such as size, color, etc.

Not bad, but it is "not natural": a door is a set: we cannot take apart its color from its size, or the fact that it opens or closes. It has both physical features (which so far we have called variables) and a behavior under different circumstances (which were the functions). All this goes together, forming an "object".

On the other hand, if we have to explain what a garage door is to someone who has not seen it before, but who knows how is the door of his house, we can say "it looks like a door of a house, but it is larger to accommodate cars, it is made of metal instead of wood ..." That is, we can describe some objects from what we know of others.

Finally, we should remember that "open" does not only refer to doors. We can also talk about opening a window or a book, for example.

With this, we have discussed about the three most important features of Object-Oriented Programming (OOP):

Ø  Encapsulation: We can not separate the behavior of the characteristics of an object. The behaviors are functions, called methods in OOP. The characteristics of an object will be variables, as the ones we have used before (we'll call them attributes). The appearance of an object in C#, as we will see a little later, is similar to a "struct".

Ø  Inheritance: Objects can inherit methods and data from others. This makes it easy to define new objects from others we had previously (as with the garage gate and the house door) and facilitates rewriting programs, as we will be able to reuse a big part of the previous ones... if they were well designed.

Ø  Polymorphism: The same method name can refer to different behaviors (such as opening a door or a book). The same idea applies for the data: both the weight of a gate and the weight of a door have the same name and refer to the same physical magnitude, but obviously have different ranges of values.

Another important concept is that of a "Class": A class is a set of objects that have common characteristics. For example, both my door and my neighbor's are doors, ie they are objects that belong to the class "door." Similarly, both a Ford Focus, a Honda Civic or a Toyota Corolla are objects that belong to the class "car".

No comments:

Post a Comment