2 Classes and Objects
A clear introduction to how object-oriented programs use classes, objects, state, methods, initialization, identity, and lifecycles to model systems.
From Classes to Objects
-oriented programs model a system as interacting objects that combine data with operations on that data. A describes the common structure and behavior of a kind of , while each is a particular instance with its own identity and state.
A useful distinction is:
A is a template describing what objects of a kind can contain and do.
An is one concrete entity created according to that template.
The same can produce many objects, each with separate instance data.
For example, a BankAccount might define an account number, an owner, a balance, and operations such as depositing or withdrawing money. The describes the capabilities of accounts; it does not represent one specific account until an is created.
Takeaway: Classes describe common structure and behavior; objects are the individual entities that use that description.
Creating Instances and Sharing References
Creating a concrete from a is called . A can be used to create multiple objects with the same available fields and methods but different values.
For example, two bank accounts may be created with different account numbers and balances. Calling a deposit operation on one account changes that account's balance, while the other account remains unchanged, because each has its own instance state.
A variable that refers to an generally stores a reference rather than the complete directly. This makes it possible for two variables to refer to one . If first and second both refer to the same account, a deposit made through second is visible when the balance is examined through first.
Takeaway: Creating objects gives a concrete instances, and references determine which an operation affects.
Fields, State, and
A is data associated with a or . An instance belongs separately to each , whereas a static or belongs to the and may be shared among all its objects.
The values of an 's instance fields at a particular time make up its state. A bank account's state might include an account number, a balance, and an open or closed status. Methods can read this state or change it.
A well-designed protects valid state by checking inputs before changing fields. For example, a withdrawal operation can reject a nonpositive amount or an amount larger than the permitted balance. Keeping internal fields private and exposing controlled operations supports .
Takeaway: State records an 's current data, and controlled access helps preserve valid state.
Methods and Behavior
A is a function defined within a . It expresses behavior associated with the or with a particular . Methods may read state, modify state, validate input, coordinate with other objects, return a result, or perform an action without returning a value.
An instance operates on a particular . Within such a , this or an equivalent keyword commonly identifies the current , so this.balance means the balance belonging to the on which the was called. Languages differ in the exact syntax; Python methods conventionally receive the instance as a first parameter named self.
A or static operates at the level and does not require a particular instance. Shared fields and static methods are most appropriate when the data or operation genuinely belongs to the as a whole.
Takeaway: Methods turn stored data into controlled behavior, with instance methods acting on particular objects and -level methods acting on the .
Initialization and Valid Objects
A runs when a new is created. Its purpose is to establish the 's initial state and ensure that required values are present. A typical creation process obtains storage, establishes default values, performs available initialization, runs the , and returns a reference to the initialized ; the exact order depends on the language.
Constructors should establish invariants: conditions that must remain true for every valid . If a bank account cannot have a negative opening balance, its should reject or correct a negative input rather than create an invalid account.
A may provide multiple constructors with different parameter lists. This practice is called overloading. Constructors may also supply default values when callers omit some initialization details.
Takeaway: Initialization is more than assigning values; it establishes the conditions that make an valid from the beginning.
Identity, Equality, and Mutation
distinguishes one from another independently of values. Two separately created accounts can have the same account number and balance while still being different objects. If a second variable is assigned a reference to the first , both variables designate one and therefore share its identity.
This distinction matters especially for mutable objects. When two references designate the same , a state change through either reference is visible through the other. By contrast, two separate objects with equal contents can change independently.
Languages may distinguish identity equality from value equality. Identity equality asks whether references designate the same , while value equality asks whether objects contain equivalent values. The exact default and comparison rules depend on the language and type.
Takeaway: Equal contents do not necessarily mean the same ; references and identity determine whether changes are shared.
The
An 's begins with a definition and proceeds through creation, initialization, use, and possible mutation. If no live part of the program can reach the through a reference, the has lost reachability.
The final handling of an unreachable depends on the language's memory-management model. In garbage-collected languages such as Java and .NET languages, an unreachable can eventually be reclaimed automatically, but reclamation is not necessarily immediate. In systems with manual memory management or deterministic resource management, a programmer or ownership system may control when storage and resources are released.
Memory reclamation is not a substitute for explicitly managing external resources such as files, sockets, or database connections. Those resources should generally be released through the language's resource-management mechanisms.
Takeaway: lifetime includes both memory and resource responsibilities, and the precise cleanup process is language-dependent.
Putting the Ideas Together
Consider a Counter with a private value . Its accepts a starting value and replaces a negative start with zero. An increment adds one to the , and a currentValue returns the current value.
If counterA is created with a starting value of three, then counterB is assigned a reference to counterA, both variables designate the same . Calling increment through counterB changes the shared 's value. Reading through counterA then produces four.
This compact example brings the concepts together:
The defines structure and behavior.
The reference identifies a particular instance.
The private stores state.
The establishes an initial valid value.
Methods provide controlled operations.
Two variable names can refer to one , so mutation through one name is visible through the other.
Takeaway: Understanding the connection among , reference, state, , , and identity explains the behavior of many -oriented programs.