See all glossary termsObject oriented programming is a way of programming where you split the program into abstract little machines called objects.
Objects are bundles of data (variables) and behavior (functions). An object can operate on its own data using its functions. For example, in Godot, a Sprite2D node has a position (a piece of data) and calling the translate function moves the sprite, changing its position.
The main idea behind objects in object-oriented programming is that they encapsulate all the code and data needed to do some useful work in your program. For example, a sprite displayed on the screen that you can move and rotate can be one object. A timer node that counts down time and emits a signal when the time is up is another object.
Originally objects were referred to as "virtual machines", and meant to communicate by sending messages to one another in a text format. Today, we kept the text interface (you write a function name to call it), but the objects are not as hermetic as they were in the original idea.
One separate feature, but that has come to be associated with opbject oriented programming is the idea of inheritance. Inheritance is a way to create new objects that are similar to existing objects. For example, in Godot, you can create a new MySprite2D
class that inherits all the methods and properties of Sprite2D
, but with additions. Today, when we talk of "object oriented programming", we often mean "inheritance". All other features of object oriented programming are found in other paradigms as well.
Inheritance is often limited. For example, if you had player units, and enemy units, you can make them both inherit from a Unit
class. But what if you want to have a player unit that can fly? You can't make it inherit from both Player
and FlyingUnit
. This is where composition comes in. This problem is so common that the "composition over inheritance" mantra has become a common saying in the programming world.
One object can be composed with multiple other objects to create more advanced and powerful entities. For example, in Godot, a playable character that can run and jump can be composed of a CharacterBody2D node to detect collisions, a Sprite2D node to display an image, an AudioStreamPlayer node to play sounds, and more. There's one object, the character body2D node, at the root of a scene that contains multiple other objects, the Sprite2D and AudioStreamPlayer nodes.
In a way, you can think of an object-oriented program as lots of small programs that work together to divide and conquer.
It's not the only way to break down the complexity of a program, but it's become the most prominent programming style in video games and a couple of other software development fields.See Also
Related terms in the Glossary
school.gdquest.com - 0.3.5-2024-11-10T20:03:57.240Z-