Classes and Objects

Classes and Objects

In object-oriented programming (OOP), the software system is organized as a collection of cooperating entities termed objects.

What is a Class?

A class is a blueprint or prototype from which objects are created. It defines:

  • Attributes (fields or properties): Represent the state or data held by the object.
  • Operations (methods): Represent the behavior that the object can perform.
public class Car {
    private String color;
    private int speed;

    public Car(String color) {
        this.color = color;
        this.speed = 0;
    }

    public void accelerate(int amount) {
        this.speed += amount;
    }
}

What is an Object?

An object is an actual instance of a class created in memory at runtime. An object has three fundamental characteristics:

  1. State: The values stored in its fields at a given point in time.
  2. Behavior: How the object acts and reacts, defined by its methods.
  3. Identity: The unique handle that distinguishes it from every other object, even if their state is identical.

When you execute:

Car car1 = new Car("Blue");

The new keyword allocates storage on the heap, invokes the constructor to initialize state, and returns a reference assigned to car1.

Exercise 1
Question

What is the core difference between a class and an object?

Show solution ↓
Solution

A class is the compile-time template or blueprint specifying structure and operations, whereas an object is a concrete runtime instance residing in memory with state and identity.

Exercise 2
Question

If two objects have identical attribute values, are they the same object?

Show solution ↓
Solution

No. They have identical state, but each object possesses a distinct identity and memory reference. In Java, == evaluates to false unless they point to the exact same reference.