Unit content
Objects and classes
Programs often need to represent entities that have both state and behavior. An object groups related data with operations that act on that data.
Because objects have identity, several references can designate the same object. Mutating that object through one reference can therefore affect what is observed through another.
Fields and methods
An object's stored values are commonly called fields, properties or attributes. Functions associated with the object are commonly called methods.
account.balance
account.deposit(amount)
A method can read or change the object's state according to the rules of the abstraction.
Classes
A class describes a family of objects that share a common structure and behavior. An object created from a class is an instance of that class.
class Rectangle
width
height
area()
Different rectangle instances can have different widths and heights while using the same area behavior.
Construction
Creating an object usually establishes its initial valid state. A constructor or initialization operation receives the information needed to create that instance. Good construction rules prevent objects from beginning in states that violate their own invariants.
Encapsulation
Encapsulation means exposing meaningful operations while keeping unnecessary implementation details behind an interface. A bank account, for example, can expose deposit and withdraw instead of allowing every caller to manipulate its internal balance representation arbitrarily.
Composition and inheritance
Objects can be combined through composition: one object contains or refers to other objects that provide part of its behavior.
Some object-oriented systems also support inheritance, where one class extends or specializes another. Inheritance can be useful, but composition is often the simpler relationship when one object merely uses another.
Objects and classes provide a way to organize state and behavior around domain concepts. They are a programming abstraction, not a requirement that every problem be modeled as an object hierarchy.