There are so many definitions of OOP out there, varying between different books, documentation and articles.
What really defines OOP?
There are so many definitions of OOP out there, varying between different books, documentation and articles.
What really defines OOP?
Ok, so in most languages, you have some way to define a data structure. It could be anything. Maybe it stores the X and Y coordinates of a Cartesian vector. And now you want to do stuff with your vectors, so you write a bunch of functions you can call like
get_vector_length(myvect)
oradd_vectors(vect1, vect2)
.In OOP, you add that kind of functionality into the data structure itself. So now you can just write
myvect.length()
orvect1 + vect2
(by implementing the+
operator for your data structure). At this point, the data structure is typically called a “class” and the functions you build into the class are “methods”.As you dig deeper into it, you learn about inheritance. When you have 2 related classes that share a lot of functionality, you can use inheritance to save a lot of duplication in your code.
In statically-typed languages, it can also come in useful to have a base class you can pack into a container, since most containers can only accept a single data type. If you had some graphics classes like
Rectangle
andCircle
that all inherit fromShape
, you could make a collection ofShape
that’s a mix of those. (In dynamically-typed languages, this tends to be less of an issue since you can put objects of any data type straight into the list. This might be why OOP isn’t approached as soon in tutorials for such languages, since it’s not as mission-critical? But it’s still a good idea to have some sort of class hierarchy where it makes sense.)