Клас (Програмування)

Шаблон коду для створення об'єктів, який визначає їхній початковий стан (змінні) та поведінку (методи).

Клас діє як користувацький тип даних. Класи підтримують три головні стовпи ООП: Інкапсуляцію (приховування внутрішнього стану за допомогою модифікаторів доступу private/public), Спадкування (створення нового класу на базі існуючого) та Поліморфізм (здатність обробляти об'єкти різних класів через спільний інтерфейс).

        graph LR
  Center["Клас (Програмування)"]:::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;

      

🧒 Простими словами

Уявіть клас як формочку для печива, а об'єкт — як саме печиво. Формочка визначає форму. Ви можете використати одну формочку, щоб зробити сотні печив. Усі вони мають однакову форму (структуру), але одне може бути з шоколадом, а інше — з глазур'ю (це їхній унікальний стан).

🤓 Expert Deep Dive

При створенні об'єкта (через конструктор) середовище виконання виділяє пам'ять у купі (heap) для змінних екземпляра. Методи зазвичай не дублюються для кожного об'єкта; у пам'яті зберігається одна копія, якій неявно передається посилання на поточний об'єкт (this або self). Динамічна диспетчеризація (поліморфізм) у таких мовах, як C++, реалізується через таблиці віртуальних методів (vtables).

❓ Часті питання

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.

🔗 Пов'язані терміни

Попередні знання:

📚 Джерела