クラス(プログラミング)

オブジェクトを作成するためのコードの設計図。状態(変数)と振る舞い(メソッド)を定義します。

クラスはカスタムデータ型として機能します。クラスはOOPの3つの主要な柱をサポートします。カプセル化(privateなどを利用して内部状態を隠す)、継承(既存のクラスから新しいクラスを作成する)、ポリモーフィズム(共通のインターフェースを通じて異なるクラスを同じクラスのインスタンスとして扱う機能)です。

        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;

      

🧒 5歳でもわかるように説明

クラスをクッキーの型抜き、オブジェクトを実際のクッキーだと考えてください。型抜きは形を決めます。同じ型抜きを使って何百枚ものクッキーを作ることができます。形はすべて同じですが、あるクッキーにはチョコチップが入っていて、別のクッキーにはアイシングがかかっているかもしれません(それが独自の状態です)。

🤓 Expert Deep Dive

インスタンス化されると、ランタイムはヒープ上にメモリを割り当てます。メソッドはオブジェクトごとに複製されるわけではなく、コンパイラが暗黙的に現在のオブジェクトへの参照(thisself)をメソッドに渡します。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.

🔗 関連用語

📚 出典