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
In Python and JS almost everything is an object, even if you think it’s not. If you only code is Python and JS that’s probably why this is hard to understand, so you may want to try studying a lower level language like C++ to better understand the difference.
An object contains multiple pieces of data together. In JS you might need an integer, so you can write let x = 3. In JS this isn’t actually a primitive integer though, it’s a Number object.
Why is using a Number object instead of just a primitive integer useful? Because it gives you a lot of other features that you don’t have to think about. Like if you added 0.1 to x, it will automatically become a float value of 1.1. In lower level languages, adding 0.1 to an integer x would just result in x not changing, it’s an integer so it can’t store that extra float value. You would have to cast it to a float to get the desired result.
You also get some methods with the object like toString, which are functions built into the object. Every Number has these so it makes it easier to call the object’s method rather than writing your own function for it and passing the integer or float to your function every time.
Yes, you can write programs without using objects at all in lower level languages. For complex projects this just gets harder and more tedious to do. Using objects lets you pack a lot of code into something simple without having to think too hard about it. Abstraction is there to make your life easier.
Latest Answers