Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 08 / Topic 1 of 12

Classes and objects: state and identity

A class is a blueprint: it describes what fields (data) and methods (behaviour) something has. An object is one instance of that blueprint, built with new. Every object gets its own copy of the fields the class declares — changing one object's fields never touches another object of the same class. Think of a class as a bank's account-opening form, and each object as one filled-in form in the vault: the form's layout is shared, but each customer's filled-in numbers are their own.

Real-world example: two customers of the same bank, modeled as Customer objects.

static class Customer {
    String name;
    String city;
    double walletBalance;
}
Customer asha = new Customer();
asha.name = "Asha Kulkarni";
asha.city = "Pune";
asha.walletBalance = 1500.0;

Customer ravi = new Customer();
ravi.name = "Ravi Shah";
ravi.city = "Mumbai";
ravi.walletBalance = 2200.0;
Asha Kulkarni from Pune, balance ₹1500.0
Ravi Shah from Mumbai, balance ₹2200.0
After top-up, Asha Kulkarni's balance: ₹2000.0
Ravi Shah's balance is unaffected: ₹2200.0
asha == ravi: false
asha == sameAsha: true
asha.walletBalance after editing through sameAsha: 0.0

Two things to notice, now true of every class you write, not only the ones built into Java:

  • asha and ravi are separate objects: changing asha.walletBalance never changes ravi.walletBalance.
  • A variable holding an object holds a reference to it, not the object itself. Customer sameAsha = asha; copies the reference, so sameAsha and asha point at the same object — editing through either name changes the one object both point at. == on objects compares references, not contents; it is not yet the "do these look equal" check you want (section 5 fixes that).

This Customer class is intentionally loose: plain public fields, no constructor, no checks. The rest of this part tightens it, piece by piece, into the kind of class real Java code actually writes.

Full program: examples/ClassesAndObjects.java.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide