Klasa (Programowanie)
Szablon kodu do tworzenia obiektów, definiujący ich stan (zmienne) i zachowanie (metody).
Klasa działa jak niestandardowy typ danych. Klasy opierają się na trzech filarach OOP: Enkapsulacji (ukrywanie stanu wewnętrznego za pomocą private/public), Dziedziczeniu (tworzenie klasy potomnej z klasy bazowej) i Polimorfizmie.
graph LR
Center["Klasa (Programowanie)"]:::main
Pre_object_oriented_programming["object-oriented-programming"]:::pre --> Center
click Pre_object_oriented_programming "/terms/object-oriented-programming"
Rel_object["object"]:::related -.-> Center
click Rel_object "/terms/object"
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧒 Wyjaśnij jak 5-latkowi
Pomyśl o klasie jak o foremce do ciastek, a o obiekcie jak o gotowym ciastku. Foremka nadaje kształt. Możesz zrobić nią setki ciastek. Wszystkie mają ten sam kształt, ale jedno może mieć kawałki czekolady, a inne lukier (to ich unikalny stan).
🤓 Expert Deep Dive
Podczas tworzenia instancji pamięć dla zmiennych obiektu jest alokowana na stercie (heap). Metody nie są duplikowane dla każdego obiektu; kompilator niejawnie przekazuje do metody referencję do obecnego obiektu (this lub self). Dynamiczne wiązanie (polimorfizm) w C++ realizowane jest za pomocą tablic metod wirtualnych (vtables).
❓ Częste pytania
What is the difference between a class and an object?
A class is the blueprint or definition (the idea). An object is the actual instance created from that blueprint (the physical thing in memory). For example, 'House' is a class, but the specific house you live in is the object.
What is a constructor in a class?
A constructor is a special method inside a class that is automatically called when a new object is created. It is used to set the initial values (state) of the object.
Do all programming languages use classes?
No. While languages like Java, C++, and Python rely heavily on classes (Object-Oriented Programming), other languages use different paradigms. For example, C uses procedural programming, Haskell uses functional programming, and JavaScript originally used prototype-based inheritance.