this post was submitted on 02 Feb 2024
52 points (89.4% liked)
Programming
17504 readers
13 users here now
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities [email protected]
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
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.)