I can’t really wrap my head around OOP. Like I understand an array and a function and a variable, but I don’t understand what an object is. Why can’t we just use functions and variables everytime we need information or code to run? I code in Python and JS mainly, so objects are truly the most important thing, but I don’t really get it. Also, isn’t every program object orientated? Even C, does it not fit the definitions? If so, how is it any different from C++?
In: Technology
You understand JavaScript arrays. In JavaScript, objects and arrays are very similar. You have multiple pieces of data packaged into one piece of data.
If you want to write a function that computes the distance between two points, you can model the points as arrays or objects:
“`
function distance(pointA, pointB) {
const dx = pointA[0] – pointB[0];
const dy = pointA[1] – pointB[1];
return Math.sqrt(dx*dx + dy*dy);
}
function distance(pointA, pointB) {
const dx = pointA.x – pointB.x;
const dy = pointA.y – pointB.y;
return Math.sqrt(dx*dx + dy*dy);
}
“`
`pointA[0]` is actually the same thing as `pointA[“0”]` and `pointA.x` is the same thing as `pointA[“x”]`. You can read `<object>.<property>` as “the <property> of <object>”, so for example “the x-component of pointA”.
In the language C, there are “structures”, which are closely related to objects. In it, the memory address of the first property (just like the first array index) is identical to the memory address of the structure and the second property is just the data after it. So it “x” and “y” are 4 bytes wide each and “pointA” lies at memory address 1000, then “x” is from 1000 to 1003 and “y” is from 1004 to 1007.
Did that help you, or are you actually interested in the difference between objects and structures?
Maybe it also helps to know, that object orientation is way for the programmer to organize code. The computer itself can’t do anything more with objects than it could do without them and when code is translated into machine language, the objects get stripped away.
Inheritance helps when you decide to extend an existing program with new data types. Then you don’t have to change the functions that *use* the new types, as long as they share the same “methods” or the same “interface” as the objects that these functions can already handle.
You can pass a new UI widget that you defined yourself to an existing `addToColumnLayout(anyUiWidget)` function, as long as any “method” `addToColumnLayout` calls on its parameter is provided by your new object — just like you can plug different electronic devices into a wall socket. If you never wanted to change the device, you wouldn’t need the shared interface. The electrons don’t care, but the people do.
Latest Answers