2.1 Class: The Blueprint
A Class is a user-defined compound type that establishes a contract for what fields an object contains and what operations it can perform. Syntactically, it encapsulates member variables, constructors, instance methods, and static helpers.
Memory Footprint of a Class
A class definition occupies space only in the process's Code / Metaspace segment (for method bytecodes and static descriptors). Main execution memory is only consumed when an object is dynamically allocated at runtime.
2.2 Object: Instance Creation and Heap Allocation
An Object is a self-contained runtime instance created from a class. In memory-managed languages like Java and C#, the statement Car c = new Car(); performs two critical actions:
- Stack Frame Allocation: Allocates a pointer / reference variable (
c) on the current function's call stack (e.g. 4 or 8 bytes). - Heap Allocation: Dynamically reserves space on the runtime heap to store the object's instance fields, object header (for locks and garbage collection metadata), and method table pointer (vptr).
2.3 Access Modifiers & Data Hiding
Access modifiers define the scope and visibility of variables, methods, and classes, forming the security boundary that prevents outside modules from manipulating internal state directly.
| Modifier | Same Class | Same Package | Subclass (Derived) | Global / Outside |
|---|---|---|---|---|
private |
Yes | No | No | No |
protected |
Yes | Yes | Yes (via inheritance) | No |
public |
Yes | Yes | Yes | Yes |
2.4 Constructors and Destructors
Constructors are special member methods invoked automatically upon object creation to initialize fields and acquire resources. They share the class name and have no return type.
Types of Constructors
- Default / Zero-Argument Constructor: Automatically generated by compilers if no explicit constructor is provided; initializes primitives to zeroes and pointers to null.
- Parameterized Constructor: Accepts caller-specified parameters to initialize fields to customized states.
- Copy Constructor: Initializes a new object as a replica of an existing instance (e.g.
Point(const Point& p)in C++).
Destructors
In languages with manual memory control like C++, a Destructor (prefixed with ~) executes automatically when an object goes out of scope or is explicitly deleted, releasing file descriptors, raw heap pointers, and socket locks. In Java/Python, garbage collection reclaims unreferenced heap space automatically.