# Classes, Objects, State and Identity — Object-Oriented Programming (OOP)

Source: https://www.skillbyai.com/en/oop/f-objects

> Distinguish classes from objects and explain state, behaviour, identity and references.

## Blueprints and instances

A **class** is a blueprint that defines what data (**fields** or attributes) and operations (**methods**) its objects have. An **object** is a concrete **instance** of a class, created at run time, typically with `new` in Java or by calling the class in Python. Every object has **state** (the current values of its fields), **behaviour** (its methods) and **identity** (it is a distinct object, even if another object has identical state). In Java, C#, Python and JavaScript, variables of class types hold **references** to objects that live on the **heap**; assigning one variable to another copies the reference, not the object, so both variables refer to the **same** object. Methods are called on objects with dot notation (`account.deposit(500)`), and inside a method the current object is available as **`this`** (Java, C++, C#) or **`self`** (Python). Classes can also have **static** members that belong to the class itself rather than any one object, such as a counter of how many objects have been created.

## Objects, references and identity

Two references to one object versus two equal but separate objects.

```java
class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
}

Student a = new Student("Asha", 91);
Student b = a;                  // copies the reference: same object
b.marks = 95;
System.out.println(a.marks);    // 95, because a and b refer to one object

Student c = new Student("Asha", 95);
System.out.println(a == c);     // false: same state, different identity
```

## A house plan and houses

A class is the architect's plan; objects are the houses built from it. Many houses share the plan but each has its own address (identity) and its own furniture (state). Giving a friend your address (a reference) does not build them a new house.

**Quiz:** After `Student b = a;` in Java, what does b refer to?

- [ ] A new copy of the object
- [ ] Nothing until it is initialised
- [ ] The Student class itself
- [x] The same object that a refers to

*Answer:* The same object that a refers to. Assignment copies the reference, so both variables point to one object.
