OOP
Theory
Machine translation, not yet reviewed by a native speaker.
Object-oriented programming is a way of building a program out of objects: each one has data (fields) and behaviour (methods).
- A class is a blueprint: "an enemy has health and can attack";
- an object is a specific instance made from the blueprint: an orc with 50 HP, a goblin with 20 HP.
The four ideas of OOP:
- Encapsulation — the data is hidden inside the object and can be changed only through its methods and properties.
You can't do
hp = -1000and bypass the rules. - Inheritance — a new class takes everything from an existing one and adds its own:
Boss : Enemy. - Polymorphism — one call, different behaviour:
enemy.Attack()works in its own way for an orc and for a mage. - Abstraction — show "what it can do", hide "how it's done": an
IDamageableinterface with aTakeDamagemethod.
In C# everything is an object of a class, even int (it's the System.Int32 struct with methods: 5.ToString()).
A C# program without classes is impossible — the top-level statements we've been writing are also
tucked away by the compiler into a Program class.
Under the hood. An object of a class lives on the heap; a variable holds only a reference to it.
Unneeded objects are cleaned up by the garbage collector (GC) — you don't write free as in C. A struct (like int, double)
is stored right in the variable and is copied on assignment.
Next up — each of these ideas in practice.