Classes and Objects in Java
In Java, a class is a blueprint or template that describes what attributes and behaviors a category of things should have. An object is a specific instance...
Building Blocks: Classes Define, Objects Exist
In Java, a class is a blueprint or template that describes what attributes and behaviors a category of things should have. An object is a specific instance created from that blueprint. The class defines the structure; the object is the actual thing in memory with real values. You can think of a class like a cookie cutter and objects as the individual cookies—many cookies can share the same shape, but each holds its own filling.
Anatomy of a Class A typical Java class contains fields (instance variables that hold the object's state), constructors (special methods that initialize new objects), instance methods (behaviors the object can perform), and optionally static members (shared across all instances). Fields are usually declared private to enforce encapsulation. Methods define what the object knows how to do.
Creating and Using Objects You create an object with the new keyword, which allocates heap memory and calls a constructor: Car myCar = new Car("Toyota", 2023). The variable myCar holds a reference—an address—to the object on the heap, not the object itself. You access fields and methods through this reference using the dot operator: myCar.start(), myCar.getSpeed(). Multiple variables can hold references to the same object, so changes through one variable are visible through the other.
Object Identity and Equality Two object variables can point to the same object (same identity) or to different objects with the same content (equal but not identical). The == operator checks identity (same memory address). The equals() method, when properly overridden, checks logical equality (same content). Failing to override equals() and hashCode() together is a common source of bugs when objects are stored in collections like HashMap or HashSet.
Code Example: class Car { String brand; int year; Car(String brand, int year) { this.brand = brand; this.year = year; } void display() { System.out.println(brand + " (" + year + ")"); } } Car c1 = new Car("Toyota", 2023); Car c2 = new Car("Toyota", 2023); c1.display(); // Toyota (2023) System.out.println(c1 == c2); // false (different objects)
Interview Tip: A common interview question is what happens in memory when you write Car c = new Car(). The answer: new allocates a Car object on the heap and invokes the constructor; the variable c on the stack holds a reference (pointer) to that heap location. Demonstrating this mental model of stack versus heap shows depth of understanding.