OOP Fundamentals
java oop object oriented programming class object constructor this keyword static instance heap stack garbage collection fields methods
Introduction
So far in this course, you've learned how to write Java programs using variables, operators, control flow, loops, arrays, and methods.
While these concepts are enough for small applications, modern enterprise software such as Spring Boot, Microservices, Banking Systems, E-commerce Platforms, and Android Applications are built using Object-Oriented Programming (OOP).
Object-Oriented Programming is a programming paradigm that organizes software around objects rather than functions.
Everything in enterprise Java revolves around objects.
For example:
- A Customer is an object.
- An Employee is an object.
- A Bank Account is an object.
- A Product is an object.
- An Order is an object.
Each object contains:
- Data (State) → Variables (Fields)
- Behavior (Actions) → Methods
In this lesson, you'll learn:
- What is OOP?
- Why OOP is Important
- Class
- Object
- Fields (Instance Variables)
- Methods
- Creating Objects
- Object Memory Model
- Constructors
thisKeyword- Instance vs Static Members
- Object Lifecycle
- Real-world Examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming approach where software is designed using objects that represent real-world entities.
Instead of focusing only on functions, OOP focuses on combining:
- Data
- Behavior
into one unit called an Object.
Example:
A Car has:
Data
- Brand
- Model
- Speed
- Color
Behavior
- Start()
- Stop()
- Accelerate()
- Brake()
In Java:
class Car {String brand;String color;void start() {System.out.println("Car Started");}}
Why OOP?
Imagine a banking application.
Without OOP:
customerName1customerName2customerName3deposit1()deposit2()deposit3()
With OOP:
Customer↓Customer Object↓Deposit()Withdraw()Transfer()
Benefits:
- Reusable code
- Easy maintenance
- High scalability
- Better security
- Real-world modeling
- Team collaboration
What is a Class?
A Class is a blueprint or template for creating objects.
It defines:
- Variables
- Methods
Example:
class Employee {String name;int age;void work() {System.out.println("Working...");}}
Think of a class as an architectural drawing.
It defines what objects will look like.
What is an Object?
An Object is an instance of a class.
Example:
Employee emp = new Employee();
Here,
Employee→ Classemp→ Object Referencenew Employee()→ Object Creation
Real-Life Analogy
Blueprint:
House Design
Actual House:
My House
Similarly,
Class↓Object↓Real Instance
Creating Multiple Objects
Employee emp1 = new Employee();Employee emp2 = new Employee();Employee emp3 = new Employee();
Each object has its own independent data.
Instance Variables (Fields)
class Student {String name;int age;}
Each object stores its own values.
Student s1 = new Student();s1.name = "Rahul";Student s2 = new Student();s2.name = "Amit";
Objects maintain separate states.
Instance Methods
class Calculator {int add(int a, int b) {return a + b;}}
Calling:
Calculator calc = new Calculator();System.out.println(calc.add(10,20));
Output:
30
Object Memory Model
When an object is created:
Student student = new Student();
Memory representation:
Stack Memorystudent│▼Heap Memory+----------------+| name = null || age = 0 |+----------------+
- Stack Memory stores the reference.
- Heap Memory stores the actual object.
This distinction is crucial for understanding Java memory management.
Constructors
A constructor initializes an object.
Example:
class Employee {Employee() {System.out.println("Object Created");}}
Creating object:
Employee emp = new Employee();
Output:
Object Created
A constructor:
- Has the same name as the class.
- Has no return type.
- Executes automatically during object creation.
Parameterized Constructor
class Student {String name;Student(String studentName) {name = studentName;}}
Creating object:
Student s = new Student("Jagannath");System.out.println(s.name);
Output:
Jagannath
The this Keyword
this refers to the current object.
Example:
class Student {String name;Student(String name) {this.name = name;}}
Here:
this.name↓Current Object Variable
It resolves ambiguity between instance variables and parameters.
Instance Members vs Static Members
class Employee {String name;static String company = "TechLearningPro";}
| Instance | Static |
|---|---|
| Belongs to object | Belongs to class |
| Separate copy per object | One shared copy |
| Accessed using object | Accessed using class |
Example:
Employee.company
instead of
emp.company
Object Lifecycle
Object lifecycle:
new↓Constructor↓Object in Heap↓Used by Program↓No Reference↓Garbage Collector Removes It
Java automatically frees unused objects using the Garbage Collector (GC).
Real-World Example: Banking System
class BankAccount {String accountHolder;double balance;void deposit(double amount) {balance += amount;}void withdraw(double amount) {balance -= amount;}}
Using it:
BankAccount account = new BankAccount();account.deposit(5000);account.withdraw(1000);System.out.println(account.balance);
Output:
4000.0
Real-World Example: Employee Management
class Employee {String name;double salary;void display() {System.out.println(name + " : " + salary);}}
Best Practices
Keep Classes Focused
Each class should have a single responsibility.
Example:
Good:
Customer
Bad:
CustomerOrderPaymentInvoiceShipping
Keep Fields Private
Expose data through methods rather than direct access.
(You'll learn Encapsulation in the next lesson.)
Use Constructors
Initialize objects properly using constructors instead of leaving fields uninitialized.
Prefer Meaningful Class Names
Examples:
- Customer
- Employee
- Product
Avoid names like:
- Data1
- TempClass
- Test123
Reuse Objects
Avoid creating unnecessary objects inside loops unless required.
Common Mistakes
Confusing Class and Object
A class is a blueprint.
An object is an instance created from that blueprint.
Forgetting to Initialize Fields
Using uninitialized fields can lead to incorrect application behavior.
Overusing Static Members
Use static only for data shared by all objects.
Creating Too Many Objects
Excessive object creation increases memory usage and garbage collection overhead.
Ignoring Constructors
Constructors help ensure objects start in a valid state.
Hands-on Exercise
Create a Java program that:
- Creates a
Studentclass with fieldsname,rollNumber, andmarks. - Adds methods to display student details.
- Creates a default constructor.
- Creates a parameterized constructor.
- Uses the
thiskeyword to initialize fields. - Creates three student objects with different values.
- Adds a static field named
schoolNameshared across all students. - Prints both instance and static data.
Summary
Object-Oriented Programming enables developers to model real-world entities using classes and objects. Understanding classes, objects, constructors, instance variables, static members, and memory management lays the foundation for advanced OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction.
Key Takeaways
- OOP models software using objects.
- A class is a blueprint; an object is an instance.
- Objects contain state (fields) and behavior (methods).
- Objects are stored in heap memory, while references are stored on the stack.
- Constructors initialize objects automatically.
- The
thiskeyword refers to the current object. - Instance members belong to objects; static members belong to the class.
- Java uses garbage collection to reclaim unused memory.
Professional Interview Questions
1What is the difference between a Class and an Object?
Professional Answer
A class is a blueprint or template that defines the properties and behaviors of objects. An object is a runtime instance of a class with its own state stored in memory. Multiple objects can be created from the same class, each maintaining independent data.
Follow-up Questions
- Can a class exist without creating an object?
- Can multiple objects share the same class definition?
Interview Tip: A commonly used analogy is Blueprint → House, where the blueprint represents the class and the house represents the object.
2What is the purpose of a Constructor?
Professional Answer
A constructor is a special member of a class that initializes objects when they are created. It has the same name as the class, has no return type, and is invoked automatically during object creation. Constructors ensure that objects start in a valid and consistent state.
Follow-up Questions
- Can constructors be overloaded?
- What happens if no constructor is defined?
Interview Tip: If no constructor is explicitly defined, Java automatically provides a default constructor (provided no other constructor exists).
3What is the difference between Instance Variables and Static Variables?
Professional Answer
Instance variables belong to individual objects, so each object has its own copy. Static variables belong to the class itself, meaning all objects share a single copy. Static variables are typically used for constants or data common to all instances.
Follow-up Questions
- Can a static method access instance variables directly?
- When should you use static fields?
Interview Tip: Remember: Instance = Per Object, Static = Shared Across All Objects.
Next Lesson: Java Encapsulation — Access Modifiers (private, public, protected, default), Getters & Setters, Data Hiding, Immutable Classes, JavaBeans Convention, Validation Logic, Real-world Banking Example, Best Practices, and advanced interview questions. This is the first of the four core pillars of OOP.