Classes and Objects
Why This File Existsβ
Object-Oriented Programming starts with classes and objects.
Many developers use them daily but donβt clearly understand:
- what a class really represents
- how objects are created in memory
- why OOP was introduced in the first place
This file builds the mental model required for all OOP concepts.
Why Object-Oriented Programming Existsβ
Before OOP:
- programs were written as large procedural code
- data and behavior were loosely connected
- maintenance was difficult as systems grew
OOP was introduced to:
- model real-world entities
- group data with behavior
- improve readability and maintainability
What Is a Classβ
A class is a blueprint or template.
It defines:
- properties (fields / variables)
- behaviors (methods)
Example:
class User {
String name;
int age;
void login() {
System.out.println("User logged in");
}
}
A class does not occupy memory by itself.
What Is an Objectβ
An object is a real instance of a class.
- Created at runtime
- Occupies memory
- Has its own state
Example:
User u1 = new User();
User u2 = new User();
Here:
u1andu2are separate objects- both follow the same class blueprint
Class vs Object (Clear Difference)β
| Aspect | Class | Object |
|---|---|---|
| Nature | Blueprint | Instance |
| Memory | No | Yes |
| Created | At compile-time | At runtime |
| Count | One definition | Many instances |
Object Creation Process (Important)β
User u = new User();
Steps:
- Memory allocated on heap
- Instance variables initialized
- Constructor executed
- Reference returned
Understanding this helps with:
- constructors
- memory management
- object lifecycle
Reference Variablesβ
User u = new User();
uis a reference variable- stores address of object
- lives on stack
- object lives on heap
Multiple references can point to same object.
Object State and Behaviorβ
- State β values of fields
- Behavior β methods
Example:
u.name = "Alex"; // state
u.login(); // behavior
OOP binds state and behavior together.
Anonymous Objectsβ
new User().login();
- Object without reference
- Used once
- Eligible for GC after use
Use sparingly for clarity.
Why This Mattersβ
Understanding classes and objects helps you:
- design better systems
- reason about memory
- understand inheritance and polymorphism
- debug reference-related issues
Common Mistakesβ
- Thinking class occupies memory
- Confusing reference with object
- Creating unnecessary objects
- Overusing anonymous objects
Best Practicesβ
- Design classes around responsibility
- Keep classes cohesive
- Avoid large βGod classesβ
- Create objects only when needed
Interview Notesβ
- Difference between class and object
- How objects are created in Java
- Where objects and references are stored
- Why OOP was introduced
Summaryβ
- Class defines structure and behavior
- Object represents real instance
- OOP starts with understanding this relationship
All other OOP concepts build on this.