Classes and Objects — Blueprint vs Instance
Introduction
Object-Oriented Programming — The Big Picture ended on the idea at the heart of object-oriented programming: keep data together with the code that works on it. What follows looks at the two things that make that possible, classes and objects: how you define the one and how you make the other.
Think of a cookie cutter and the cookies it makes. The cutter decides the shape, but it is not a cookie itself. Each time you press it into the dough you get a new cookie of that shape, and you can decorate each one differently, sprinkles on one and chocolate on another.
In object-oriented code the class plays the cutter. It is a blueprint that says what data each object will hold (its attributes) and what each object can do (its methods). An object, also called an instance, is one concrete thing made from that blueprint, holding values of its own.
Most of what follows in this course is built on these two ideas: Encapsulation — Data Hiding Done Right, Inheritance — Code Reuse & Hierarchies and Polymorphism — Compile-Time vs Runtime over the next few lessons, the design principles after them, and every pattern in Design Patterns - Low Level Design.
What is a Class?
A class is a type you define yourself. It describes two things about the objects made from it.
Attributes, also called fields or properties, are the data each object holds. A bank account has an owner and a balance.
Methods are what each object can do. A bank account can take a deposit, allow a withdrawal and report its balance.
The class describes the data, but the values live in the objects. BankAccount says that every account has an owner and a balance; it does not hold Alice's 5000.00 or Bob's 1200.00. Those belong to the accounts made from it. An architect's blueprint works the same way: it describes a house, and nobody can live in it.
A class can also keep a value of its own that every object shares. Java calls these static fields or class variables and says "They are associated with the class, rather than with any object." Python's tutorial draws the same line: "instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class". The bank accounts here hold only values of their own.
| Concept | Real-world analogy | In the code |
|---|---|---|
| Class | An architect's blueprint | class BankAccount |
| Attributes | What the blueprint says each house has | owner, balance |
| Methods | What the blueprint says each house can do | deposit(), withdraw() |
| Object | One house built from the blueprint | BankAccount("Alice", 5000.0) |
What is an Object?
An object is a concrete thing made from a class. It holds values of its own and can do what its class says. Making an object from a class is called instantiation. In Java the new operator does it, and the Java tutorial describes what happens: "The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory." In Python you call the class as you would call a function; its tutorial puts it as "Class instantiation uses function notation."
Every object has three things.
State is the current values of its attributes: for a bank account, the owner's name and the balance.
Behavior is what its methods let it do: take a deposit, allow a withdrawal, report its balance.
Identity is what makes it this object and no other. Two accounts can both belong to Alice and both hold 5500.00 and still be two separate accounts, so that a deposit into one leaves the other as it was. Python's reference says "Every object has an identity, a type and a value." and adds that "The is operator compares the identity of two objects". Java's == does the same for objects: it is true when both sides "refer to the same object or array".
Identity matters most when you decide which things in a system are told apart by who they are and which only by their values. Entities vs Value Objects — Identity and Equality takes that up.
The picture shows the class as a blueprint that holds no values, and four objects made from it, each holding its own.

Your First Class, Step by Step
Here is a BankAccount class and a short program that makes objects from it. Read it once from top to bottom; the notes after it go through each part.
# A class is a blueprint: it says what every bank account knows and can do
class BankAccount:
"""Blueprint for a bank account.
Attributes define what every BankAccount KNOWS:
- owner: the name of the account holder
- balance: the current balance in dollars
Methods define what every BankAccount CAN DO:
- deposit: add money
- withdraw: take money out, if there is enough
- get_owner, get_balance: report what it knows
"""
def __init__(self, owner: str, balance: float = 0.0) -> None:
# The constructor runs when a new object is made; self is that object
self.owner = owner # attribute: who owns this account
self.balance = balance # attribute: how much money is in it
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self.balance += amount
print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")
def withdraw(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Withdrawal amount must be positive")
if amount > self.balance:
raise ValueError(f"Insufficient funds. Balance: ${self.balance:.2f}")
self.balance -= amount
print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")
def get_owner(self) -> str:
return self.owner
def get_balance(self) -> float:
return self.balance
# Creating objects (instances): each call makes a new, separate object
alice_account = BankAccount("Alice", 5000.0) # object 1
bob_account = BankAccount("Bob", 1200.0) # object 2
charlie_account = BankAccount("Charlie") # object 3, balance 0.00
# Each object has its own state: changing one leaves the others alone
alice_account.deposit(500.0) # only Alice's balance changes
bob_account.withdraw(200.0) # only Bob's balance changes
print()
for account in (alice_account, bob_account, charlie_account):
print(f"{account.get_owner()}'s balance: ${account.get_balance():.2f}")
# Identity: a second object with the same state is still another object
twin = BankAccount("Alice", 5500.0)
same_state = (twin.get_owner() == alice_account.get_owner()
and twin.get_balance() == alice_account.get_balance())
print()
print(f"Same owner and balance as Alice's account? {'yes' if same_state else 'no'}")
print(f"The same object? {'yes' if twin is alice_account else 'no'}")import java.util.Locale;
// A class is a blueprint: it says what every bank account knows and can do
public class BankAccount {
// Attributes: what every BankAccount KNOWS
private String owner;
private double balance;
// Constructor: runs when a new object is made; this is that object
public BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
// A second constructor: an account opened with no money starts at 0
public BankAccount(String owner) {
this(owner, 0.0);
}
// Methods: what every BankAccount CAN DO
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be positive");
}
this.balance += amount;
System.out.printf(Locale.ROOT, "Deposited $%.2f. New balance: $%.2f%n",
amount, this.balance);
}
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive");
}
if (amount > this.balance) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Insufficient funds. Balance: $%.2f", this.balance));
}
this.balance -= amount;
System.out.printf(Locale.ROOT, "Withdrew $%.2f. New balance: $%.2f%n",
amount, this.balance);
}
public String getOwner() {
return this.owner;
}
public double getBalance() {
return this.balance;
}
public static void main(String[] args) {
// Each 'new' makes a new, separate object
BankAccount aliceAccount = new BankAccount("Alice", 5000.0); // object 1
BankAccount bobAccount = new BankAccount("Bob", 1200.0); // object 2
BankAccount charlieAccount = new BankAccount("Charlie"); // object 3
// Each object has its own state: changing one leaves the others alone
aliceAccount.deposit(500.0); // only Alice's balance changes
bobAccount.withdraw(200.0); // only Bob's balance changes
System.out.println();
BankAccount[] accounts = {aliceAccount, bobAccount, charlieAccount};
for (BankAccount account : accounts) {
System.out.printf(Locale.ROOT, "%s's balance: $%.2f%n",
account.getOwner(), account.getBalance());
}
// Identity: a second object with the same state is still another object
BankAccount twin = new BankAccount("Alice", 5500.0);
boolean sameState = twin.getOwner().equals(aliceAccount.getOwner())
&& twin.getBalance() == aliceAccount.getBalance();
System.out.println();
System.out.println("Same owner and balance as Alice's account? "
+ (sameState ? "yes" : "no"));
System.out.println("The same object? " + (twin == aliceAccount ? "yes" : "no"));
}
}#include <cstdio>
#include <initializer_list>
#include <stdexcept>
#include <string>
#include <utility>
// A class is a blueprint: it says what every bank account knows and can do
class BankAccount {
public:
// Constructor: runs when a new object is made; this is that object
BankAccount(std::string owner, double balance)
: owner_(std::move(owner)), balance_(balance) {}
// A second constructor: an account opened with no money starts at 0
explicit BankAccount(std::string owner) : BankAccount(std::move(owner), 0.0) {}
// Methods: what every BankAccount CAN DO
void deposit(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Deposit amount must be positive");
}
balance_ += amount;
std::printf("Deposited $%.2f. New balance: $%.2f\n", amount, balance_);
}
void withdraw(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Withdrawal amount must be positive");
}
if (amount > balance_) {
char message[64];
std::snprintf(message, sizeof message, "Insufficient funds. Balance: $%.2f",
balance_);
throw std::invalid_argument(message);
}
balance_ -= amount;
std::printf("Withdrew $%.2f. New balance: $%.2f\n", amount, balance_);
}
const std::string& getOwner() const { return owner_; }
double getBalance() const { return balance_; }
private:
// Attributes: what every BankAccount KNOWS
std::string owner_;
double balance_;
};
int main() {
// Each declaration makes a new, separate object
BankAccount aliceAccount("Alice", 5000.0); // object 1
BankAccount bobAccount("Bob", 1200.0); // object 2
BankAccount charlieAccount("Charlie"); // object 3
// Each object has its own state: changing one leaves the others alone
aliceAccount.deposit(500.0); // only Alice's balance changes
bobAccount.withdraw(200.0); // only Bob's balance changes
std::printf("\n");
for (const BankAccount* account : {&aliceAccount, &bobAccount, &charlieAccount}) {
std::printf("%s's balance: $%.2f\n", account->getOwner().c_str(),
account->getBalance());
}
// Identity: a second object with the same state is still another object
BankAccount twin("Alice", 5500.0);
bool sameState = twin.getOwner() == aliceAccount.getOwner() &&
twin.getBalance() == aliceAccount.getBalance();
std::printf("\n");
std::printf("Same owner and balance as Alice's account? %s\n",
sameState ? "yes" : "no");
// Two objects are the same object only if they sit at the same address
std::printf("The same object? %s\n", &twin == &aliceAccount ? "yes" : "no");
return 0;
}// A class is a blueprint: it says what every bank account knows and can do
class BankAccount {
// Attributes: what every BankAccount KNOWS
private owner: string;
private balance: number;
// Constructor: runs when a new object is made; this is that object.
// TypeScript allows one constructor body, so a default value of 0 does the job
// of Java's second constructor.
constructor(owner: string, balance: number = 0) {
this.owner = owner;
this.balance = balance;
}
// Methods: what every BankAccount CAN DO
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Deposit amount must be positive");
}
this.balance += amount;
console.log(
`Deposited $${amount.toFixed(2)}. New balance: $${this.balance.toFixed(2)}`,
);
}
withdraw(amount: number): void {
if (amount <= 0) {
throw new Error("Withdrawal amount must be positive");
}
if (amount > this.balance) {
throw new Error(`Insufficient funds. Balance: $${this.balance.toFixed(2)}`);
}
this.balance -= amount;
console.log(
`Withdrew $${amount.toFixed(2)}. New balance: $${this.balance.toFixed(2)}`,
);
}
getOwner(): string {
return this.owner;
}
getBalance(): number {
return this.balance;
}
}
// Each 'new' makes a new, separate object
const aliceAccount = new BankAccount("Alice", 5000.0); // object 1
const bobAccount = new BankAccount("Bob", 1200.0); // object 2
const charlieAccount = new BankAccount("Charlie"); // object 3
// Each object has its own state: changing one leaves the others alone
aliceAccount.deposit(500.0); // only Alice's balance changes
bobAccount.withdraw(200.0); // only Bob's balance changes
console.log();
for (const account of [aliceAccount, bobAccount, charlieAccount]) {
console.log(`${account.getOwner()}'s balance: $${account.getBalance().toFixed(2)}`);
}
// Identity: a second object with the same state is still another object
const twin = new BankAccount("Alice", 5500.0);
const sameState =
twin.getOwner() === aliceAccount.getOwner() &&
twin.getBalance() === aliceAccount.getBalance();
console.log();
console.log(`Same owner and balance as Alice's account? ${sameState ? "yes" : "no"}`);
console.log(`The same object? ${twin === aliceAccount ? "yes" : "no"}`);using System;
using static System.FormattableString;
// A class is a blueprint: it says what every bank account knows and can do
public class BankAccount
{
// Attributes: what every BankAccount KNOWS
public string Owner { get; }
public double Balance { get; private set; }
// Constructor: runs when a new object is made; this is that object
public BankAccount(string owner, double balance)
{
Owner = owner;
Balance = balance;
}
// A second constructor: an account opened with no money starts at 0
public BankAccount(string owner) : this(owner, 0.0)
{
}
// Methods: what every BankAccount CAN DO
public void Deposit(double amount)
{
if (amount <= 0)
{
throw new ArgumentException("Deposit amount must be positive");
}
Balance += amount;
Console.WriteLine(
Invariant($"Deposited ${amount:F2}. New balance: ${Balance:F2}"));
}
public void Withdraw(double amount)
{
if (amount <= 0)
{
throw new ArgumentException("Withdrawal amount must be positive");
}
if (amount > Balance)
{
throw new ArgumentException(
Invariant($"Insufficient funds. Balance: ${Balance:F2}"));
}
Balance -= amount;
Console.WriteLine(
Invariant($"Withdrew ${amount:F2}. New balance: ${Balance:F2}"));
}
}
public static class Program
{
public static void Main()
{
// Each 'new' makes a new, separate object
var aliceAccount = new BankAccount("Alice", 5000.0); // object 1
var bobAccount = new BankAccount("Bob", 1200.0); // object 2
var charlieAccount = new BankAccount("Charlie"); // object 3
// Each object has its own state: changing one leaves the others alone
aliceAccount.Deposit(500.0); // only Alice's balance changes
bobAccount.Withdraw(200.0); // only Bob's balance changes
Console.WriteLine();
foreach (var account in new[] { aliceAccount, bobAccount, charlieAccount })
{
Console.WriteLine(
Invariant($"{account.Owner}'s balance: ${account.Balance:F2}"));
}
// Identity: a second object with the same state is still another object
var twin = new BankAccount("Alice", 5500.0);
bool sameState = twin.Owner == aliceAccount.Owner
&& twin.Balance == aliceAccount.Balance;
Console.WriteLine();
Console.WriteLine("Same owner and balance as Alice's account? "
+ (sameState ? "yes" : "no"));
// On two class objects, ReferenceEquals asks whether they are one object
Console.WriteLine("The same object? "
+ (ReferenceEquals(twin, aliceAccount) ? "yes" : "no"));
}
}package main
import (
"errors"
"fmt"
)
// BankAccount is a blueprint: it says what every bank account knows and can do.
// Its attributes, what every BankAccount KNOWS:
type BankAccount struct {
owner string
balance float64
}
// NewBankAccount makes a new account: Go has no constructors, so a function does it
func NewBankAccount(owner string, balance float64) *BankAccount {
return &BankAccount{owner: owner, balance: balance}
}
// Deposit and the methods below: what every BankAccount CAN DO
func (a *BankAccount) Deposit(amount float64) error {
if amount <= 0 {
return errors.New("deposit amount must be positive")
}
a.balance += amount
fmt.Printf("Deposited $%.2f. New balance: $%.2f\n", amount, a.balance)
return nil
}
func (a *BankAccount) Withdraw(amount float64) error {
if amount <= 0 {
return errors.New("withdrawal amount must be positive")
}
if amount > a.balance {
return fmt.Errorf("insufficient funds. Balance: $%.2f", a.balance)
}
a.balance -= amount
fmt.Printf("Withdrew $%.2f. New balance: $%.2f\n", amount, a.balance)
return nil
}
func (a *BankAccount) Owner() string { return a.owner }
func (a *BankAccount) Balance() float64 { return a.balance }
func main() {
// Each call makes a new, separate object
aliceAccount := NewBankAccount("Alice", 5000.0) // object 1
bobAccount := NewBankAccount("Bob", 1200.0) // object 2
// Go has no default arguments, so Charlie's empty account passes 0
charlieAccount := NewBankAccount("Charlie", 0) // object 3
// Each object has its own state: changing one leaves the others alone
if err := aliceAccount.Deposit(500.0); err != nil { // only Alice's balance changes
fmt.Println(err)
}
if err := bobAccount.Withdraw(200.0); err != nil { // only Bob's balance changes
fmt.Println(err)
}
fmt.Println()
for _, account := range []*BankAccount{aliceAccount, bobAccount, charlieAccount} {
fmt.Printf("%s's balance: $%.2f\n", account.Owner(), account.Balance())
}
// Identity: a second object with the same state is still another object
twin := NewBankAccount("Alice", 5500.0)
sameState := twin.Owner() == aliceAccount.Owner() &&
twin.Balance() == aliceAccount.Balance()
fmt.Println()
fmt.Printf("Same owner and balance as Alice's account? %s\n", yesNo(sameState))
// Two pointers are equal only when they point to the same object
fmt.Printf("The same object? %s\n", yesNo(twin == aliceAccount))
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}It prints:
Deposited $500.00. New balance: $5500.00
Withdrew $200.00. New balance: $1000.00
Alice's balance: $5500.00
Bob's balance: $1000.00
Charlie's balance: $0.00
Same owner and balance as Alice's account? yes
The same object? no
Here is what each part does.
class BankAccount declares the blueprint. Every account knows its owner and its balance, and can deposit, withdraw and report both.
The constructor runs by itself each time an object is made and gives the new object its starting values. In Python it is the method named __init__, which Python calls on every new object; in Java it is the method with the class's own name. Java's second constructor, given only an owner, starts the balance at 0, and Python gets the same from a default value. Constructors — Default, Parameterized, Copy covers constructors in full.
self in Python and this in Java mean the object a method was called on. When alice_account.deposit(500.0) runs, self is Alice's account, so only her balance changes.
BankAccount("Alice", 5000.0) is instantiation: it makes a new object with its own copy of the attributes.
Independence. Alice's deposit leaves Bob's balance as it was, and Bob's withdrawal leaves Alice's. Each object holds its own state.
Identity. twin is made with Alice's owner and balance, so the program finds the same values, yet it is still another object, and the last line prints no. Python asks with is and Java with ==, and each of the other languages has its own way, named in a comment in its listing.
Watch the Program Run
The same program, one statement at a time. Press "Next step" to make each account, then to make the deposit and the withdrawal, and watch which balance moves. Before each of the last two lines is printed, predict what it will say with "yes" or "no".

Class vs Object: The Complete Picture
Here is the whole comparison in one place.
| Aspect | Class | Object |
|---|---|---|
| What it is | A blueprint: a type you define | One concrete thing made from it |
| Memory | Written once, however many objects there are | Each object takes memory of its own |
| Data | Says what data exists, such as balance: float | Holds the values, such as balance = 5500.0 |
| How many | One | As many as the program makes |
| Creation | class BankAccount: | BankAccount("Alice", 5000.0) |
| Analogy | A cookie cutter | The cookies |
| Car analogy | The design of a car: an engine, four wheels, a color | Your own red Toyota Camry |
You write a class once and make as many objects from it as you need. A bank would have one BankAccount class and an object for every customer's account, each keeping its own balance. The rules live in one place, and every object follows them.
Common Mistakes
Mistake 1: calling a method on the class instead of on an object. "I wrote a Dog class, so I can call Dog.bark()." A method like bark works on one object's data, so it needs an object to work on. Python stops the call with TypeError: Dog.bark() missing 1 required positional argument: 'self', and Java refuses to compile it: non-static method bark() cannot be referenced from a static context. Make an object first, with Dog().bark() in Python or new Dog().bark() in Java. Some methods do belong to the class itself, the static methods, but the usual way is to make an object and call its methods.
Mistake 2: thinking objects share state. "I deposited money into Alice's account, so every account has more now." Each object has its own copy of the attributes, as the program above showed: Alice's deposit left Bob's balance at 1000.00. A change to one object reaches another only if you write code that does it.
Mistake 3: making a class when plain functions would do. A MathHelper class with nothing but add() and multiply() holds no state, and in Python a module of plain functions does the same job with less code. Java has no functions outside a class, so its own library keeps such helpers as static methods of a class: "The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions." A class earns its place when its objects hold state and behavior together. Telling when to make one is a skill this course keeps coming back to, in Code Smells — Recognizing Bad Design among others.
Real-World Modeling with Classes
Classes model the things a system is about. Here are five from the problems in Design Problems - Low Level Design, with some of the attributes and methods each one has there.
| Class, and its problem | Attributes (state) | Methods (behavior) |
|---|---|---|
ParkingSpot, parking lot | id, spotType, isOccupied, vehicle | park(), unpark(), isAvailable() |
Piece, chess | color, pieceType, hasMoved | getValidMoves(), setMoved() |
Ride, ride sharing (Uber) | pickup, destination, state | matchDriver(), startRide(), cancel() |
Playlist, music streaming (Spotify) | name, owner, isPublic, songs | addSong(), removeSong() |
Wallet, digital wallet | balance, transactions | credit(), debit() |
Notice the pattern: the nouns of a problem tend to become classes, the facts about them attributes, and the verbs methods. The Object Discovery Process — Nouns, Verbs, Relationships turns that into a way of finding the classes in a problem statement.
Key Takeaways
- A class is a blueprint: it describes the attributes (data) and methods (behavior) of its objects, while the values themselves live in the objects.
- An object, or instance, is one thing made from a class, and making it is called instantiation:
BankAccount("Alice", 5000.0)in Python,new BankAccount("Alice", 5000.0)in Java. - Every object has state (its current values), behavior (its methods) and identity (it is itself and no other, even when another object holds equal values).
- Objects made from the same class are independent: changing one leaves the others alone.
- Constructors — Default, Parameterized, Copy comes next: how an object gets its starting values.