OOP (Java)
OOP (Java)
Fundamentals of OOP
• What is OOP?
“OOP, or Object-Oriented Programming, is a programming approach that organizes code using
objects and classes.
A class is like a blueprint, and an object is a real-world instance of that blueprint.
OOP makes it easier to manage and scale programs by grouping related data and functions together.
It is based on 4 key principles:
1. Encapsulation – Hiding internal data and exposing only necessary parts using access modi ers (like private,
public).
2. Abstraction – Hiding complex logic and showing only essential features to the user.
3. Inheritance – Reusing properties and behaviors from one class in another.
4. Polymorphism – One function or object behaving differently in different contexts.
For example, if I have a class Car with a method drive(), I can reuse and modify it in a SportsCar class using
inheritance and overriding.
OOP is widely used in real-world software systems because it promotes reusability, modularity, and
maintainability.”**
• Need for OOP over Procedural Programming
Procedural programming is good for small programs, but when applications get large and complex, it
becomes hard to manage because everything is based on functions and global data.
OOP solves this by organizing code using classes and objects. It makes the code more reusable, maintainable, and
secure. Concepts like encapsulation, inheritance, abstraction, and polymorphism help developers build real-world,
modular, and scalable software.
That’s why OOP is preferred over procedural programming in most large-scale software systems.
◦ Class
A class is a blueprint or template used to create objects.
It de nes what data (variables) and functions (methods) the object will have.
◦ Object
An object is an instance of a class.
It represents a real-world entity created from the blueprint provided by the class.
◦ Encapsulation
Encapsulation is the process of binding data and the methods that operate on that data
into a single unit (a class), and restricting direct access to some parts of the object using access modi ers.
fi
fl
fi
fi
In short:
🔒 "Data hiding + data protection + one unit = Encapsulation"
🎯 Real-Life Example:
🔑 Think of a capsule medicine:
• It has ingredients inside (data)
• It has a protective shell (access control)
• You can take it, but you don’t see or touch what’s inside
That’s Encapsulation!
◦ Abstraction
Abstraction means showing only the important parts of an object and hiding the
unnecessary details.
🧠 Focus on "what it does", not "how it does it."
🎯 Real-Life Example:
When you:
• Use a mobile phone, you just tap to call — you don’t see the wiring, signal processing, etc.
• That's abstraction: You see only features, not the complex internal code.
◦ Inheritance
Inheritance is an OOP concept where one class (child or derived class) inherits the
properties and behaviors (data and methods) of another class (parent or base class).
🔑 In Short:
• It allows reusing code from one class into another.
• The child class can use, modify, or extend the functionality of the parent class.
• It helps achieve code reusability and a logical hierarchy.
🎯 Real-Life Example:
Think of a Parent and Child:
• Parent has some features (like surname, property).
• Child inherits them, and can also have own features.
Just like that — in code:
• Parent class = common logic
• Child class = inherits + adds more
◦ Polymorphism
Polymorphism means More than one form of an object
One person can behave differently based on the situation or role they are in.
• When he is in college → he behaves as a Student
• When he is at home → he behaves as a Son
• When he is at a part-time job → he behaves as an Employee
• When he’s playing cricket → he’s a Player
✅ Class in Java
class Student {
String name;
fi
int rollNo;
void showDetails() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}
}
protected ✅ ✅ ✅ ❌
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌
• Constructors
fi
fi
fi
A constructor is a special method that is automatically called when an object is created.
It is used to initialize the object’s data members (like name, age, etc.).
✅ Java
🔹 Default Constructor
If you don’t de ne any constructor, Java gives you a default one automatically.
class Student {
String name;
int age;
Student() {
name = "Default";
age = 0;
}
}
🔹 Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}
🔹 Copy Constructor (manual in Java)
Student(Student s) {
this.name = s.name;
this.age = s.age;
}
• Destructor (C++)
A Destructor is a special method that is called automatically when an object is destroyed.
It is used to clean up memory or release resources (like les, network, database)
🧠 Why is it needed?
Imagine you're opening a le in your program. Once the work is done, you must close it to avoid memory leaks.
👉 Destructor handles that automatically when the object is deleted.
Type Meaning
• this pointer
✅ Java: this keyword
🔹 Example:
class Student {
String name;
Student(String name) {
this.name = name; // 'this' refers to current object
}
void show() {
System.out.println("Name: " + this.name);
}
}
🤝 Summary Table:
🔹 1. final Variable
👉 You cannot change the value after assignment.
final int age = 18;
age = 20; // ❌ Error: Cannot assign a value to final variable
Real life example:
If your birth year is nal → it never changes.
🔹 2. final Method
👉 You cannot override it in a subclass (child class).
class Parent {
final void show() {
System.out.println("Hello from Parent");
fi
}
}
🔹 3. final Class
👉 You cannot inherit (extend) it.
final class Car {
void run() {
System.out.println("Car is running");
}
}
// class BMW extends Car { } ❌ Error: Cannot inherit from final class
• Object lifecycle
🟢 3. Encapsulation
• What is encapsulation?
Encapsulation means binding data and methods together into one unit (a class), and hiding
internal details from the outside.
🎯 Key Points:
• Keeps data safe from outside access.
🧠 Real-Life Example:
Think of a bank ATM:
• Money = Data
• ATM = Class
🔸 Java: Encapsulation
class Student {
private String name; // private variable
public void setName(String n) { // setter
name = n;
}
public String getName() { // getter
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Siddhesh");
System.out.println(s.getName());
}
}
• Data hiding
Data Hiding means protecting internal data of a class from direct access by the outside world.
✅ Real-Life Example:
• But you can’t see or directly change the internal vote count (data)
• Bene ts of encapsulation
🟢 4. Abstraction
• What is abstraction?
“Abstraction is the process of hiding internal details and showing only what is necessary.”
✅ Why is Abstraction Useful?
• To reduce complexity
• To focus on what’s important
• To use things without knowing internal code
🎯 Real-life Examples:
1. Mobile Phone
◦ You press the call button — don't need to know how the signal travels.
3. ATM
◦ You enter the amount — you don’t see the banking logic.
fi
fi
fi
• Abstract classes
An abstract class is a class that cannot be instantiated (you can't create objects of it) and is meant to be inherited by
other classes.
It may contain:
• Abstract methods (no body)
• Normal methods (with body)
An abstract class is like a blueprint. It de nes what should be done, but not how to do it — the child class will de ne the
actual implementation
🎯 Real-Life Example:
Imagine a base class called Animal:
• All animals can make sound, but each one does it differently.
• So Animal class has a method makeSound() but doesn’t de ne how.
• Subclasses like Dog, Cat, Cow will de ne it.
🔹 Java:
abstract class Animal {
abstract void makeSound(); // Abstract method
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound();
}
}
• Interface
An Interface is a completely abstract class — it only has method declarations (no body), and no variables (except
constants).
It de nes what a class must do, but not how.
🔹 Java Interface Example:
interface RemoteControl {
void turnOn();
void turnOff();
}
✅ Purpose Partial abstraction (some code + some rules) Full abstraction (only rules, no code)
🏷 Keyword abstract (Java), pure virtual in C++ interface (Java), ABC in Python
🧩 Variables Can have instance variables Only constants ( nal + static) in Java
🧪 Multiple
❌ Not supported in Java (Yes in C++) ✅ Yes, multiple interfaces can be implemented
Inheritance
🏗 Constructors ✅ Yes ❌ No
1⃣ ATM Machine
2⃣ Mobile Phone
• When to use abstraction
I use abstraction when I want to hide complexity, enforce rules through interfaces or abstract
classes, and create a clear separation between what something does and how it’s done. It helps build
scalable, modular, and maintainable code.
🟢 5. Inheritance
• What is inheritance?
Inheritance is an OOP concept where one class (child) gets the properties and behaviors (data and methods) of
another class (parent).
🎯 Real-Life Example:
👨 Parent Class → Vehicle
• Methods: start(), stop()
🧒 Child Class → Car
• Inherits start() and stop() from Vehicle
• Can also have its own method like openTrunk()
• Types of inheritance:
fi
◦ Single
When a class inherits from only one parent class, it is called Single Inheritance.
✅ Example:
Java:
class Animal {
void speak() {
System.out.println("Animal speaks");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.speak();
}
}
◦ Multilevel
Java:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.sound();
p.bark();
p.weep();
}
}
◦ Hierarchical
Java:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
Cat c = new Cat();
c.sound();
c.meow();
}
}
interface Mother {
void cooking();
}
class Main {
public static void main(String[] args) {
Child c = new Child();
c.farming();
c.cooking();
}
}
🔁 Key Rule:
• Same method name
• Same number & type of parameters
• In inheritance only
class Animal {
void speak() {
System.out.println("Animal speaks");
}
}
class Dog extends Animal {
@Override
void speak() {
System.out.println("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.speak(); // Output: Dog barks
}
}
• Ambiguity in multiple inheritance
Ambiguity occurs in multiple inheritance when two parent classes have methods or variables
with the same name, and the child class inherits both — so the compiler gets confused about
which one to use.
🟢 6. Polymorphism
• What is polymorphism?
Polymorphism means one name, many forms. It allows the same function or method name to behave differently
depending on the object or input
✅ Polymorphism in Java
• Meaning: The ability of an object to take many forms.
◦ Example:
class MathOp {
Example:
class Animal {
• In C++, a friend function can access private and protected members of a class, even
though it is not part of the class.
• If one class needs to use data from another class, Java provides alternatives like:
3. Package-private (default access modi er) – classes in the same package can access
each other’s members if not marked private.
🔹 When to use?
• When you want to provide a common base with partial implementation.
• To de ne shared behavior, but leave details to child classes.
✅ Syntax:
abstract class Animal {
abstract void sound(); // abstract method (no body)
void sleep() {
System.out.println("Sleeping...");
fi
fi
fi
fi
}
}
🔹 When to use?
• To prevent other classes from modifying or extending your class.
• Common for security or utility/helper classes.
✅ Syntax:
final class MathUtils {
public static int square(int x) {
return x * x;
}
}
• It helps in code reusability and type safety (no need to write the same method for int,
String, double, etc.).
🔹 Example
class Test {
// Generic Method
public <T> void printData(T data) {
System.out.println("Data: " + data);
}
t.printData(10); // Integer
t.printData("Hello"); // String
t.printData(12.5); // Double
}
}
🟢 8. Object Relationships
🎯 Real-life Example:
• A Dog IS-A Animal
• A Car IS-A Vehicle
• A Student IS-A Person
These represent "is-a" relationships because the child class inherits properties of the parent class.
🎯 Real-life Examples:
• A Car HAS-A Engine
• A Library HAS-A Book
• A Student HAS-A Address
🧠 Interview One-liner:
“HAS-A represents composition, where one class contains another class object. For example, a Car HAS-A Engine. It
promotes code reuse and exibility.”
• Aggregation vs Composition
• Object Dependency
Object dependency means one object depends on another object to do its job.
In simple words:
If Class A uses Class B, then A is dependent on B.
🎯 Real-life Example:
• A Car depends on an Engine
🟢 9. Memory Management
• Stack vs Heap
fl
fi
Feature Stack Heap
Memory used for static memory Memory used for dynamic memory
📦 De nition allocation allocation
⚙ Usage Stores method calls, local variables Stores objects and dynamic variables
⏱ Access Very fast Slower than stack
speed
🔄 Memory Limited and small Larger than stack
size
Memory
Part Description
Location
Object data Heap Actual data ( elds/attributes) of the object
Object A pointer or reference to the object (variable in
Stack
reference method)
🧠 Simple De nition:
“It is a technique to handle unexpected runtime errors in a safe and controlled way.”
• Divide by zero
• Network failure
• Invalid input
✅ Java: try-catch-finally
🧾 Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle that exception
} finally {
// Code that always runs (even if error happens or not)
fi
fi
fi
}
💡 Example:
public class Main {
public static void main(String[] args) {
try {
int a = 5 / 0; // Error: divide by zero
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This will always run.");
}
}
}
• throw/throws
🧨 What is throw?
throw is used to actually throw an exception (manually) during program execution.
✅ Syntax:
throw new ExceptionType("message");
🔹 Example:
public class Main {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("Eligible to vote");
}
}
📢 What is throws?
throws is used in method signature to declare that a method might throw an exception.
✅ Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// code
}
🔹 Example:
public class Main {
static void checkFile() throws IOException {
throw new IOException("File not found");
}
🔹 super Keyword
🔸 Refers to the parent (super) class — used in inheritance.
✅ Use cases:
1. To call parent class constructor.
2. To access parent class variables or methods.
fi
fi
fi
🧾 Simple Example:
class Person {
String name = "John";
void show() {
System.out.println("Person Name: " + name);
}
}
void display() {
System.out.println("Student Name: " + name); // Siddhesh
System.out.println("Person Name: " + super.name); // John
super.show(); // Call parent class method
}
}
👉 We write the Java program only once, and it can run on any operating system without changing
the code.
👉 This is possible because Java code is compiled into bytecode, and the JVM (Java Virtual
Machine) on each OS understands and runs that bytecode.
== (double equals)
Example:
.equals() method
String
• Example:
String s = "Hello";
StringBuilder
StringBuffer
Reason:
• Because primitive data types (int, char, boolean, etc.) are not objects.
• If Java had no primitives and everything was an object, it would be fully OOP, but it uses
primitives for performance reasons.
• De nition: A set of classes and interfaces that provide ready-made data structures and
algorithms to store, manage, and manipulate groups of objects.
• Includes List, Set, Queue, Map, and related utility classes like Collections and
Arrays.
1. List
• Ordered collection (maintains insertion order)
• Allows duplicates
• Access by index
2. Set
• Unordered collection (no guarantee of order, except LinkedHashSet)
• No duplicates allowed
3. Map
• Stores key-value pairs
1. ArrayList
• Implements: List interface
2. LinkedList
• Implements: List and Deque interfaces
• Memory: More memory used (each node stores data + pointers to next/previous)
1. HashMap
• Stores: Key-Value pairs
2. TreeMap
• Stores: Key-Value pairs
3. LinkedHashMap
• Stores: Key-Value pairs
1. HashSet
• Stores: Unique elements (no duplicates)
• Package: java.util.concurrent
• Key Feature:
◦ Multiple threads can read and write safely at the same time.
◦ Uses segment locking / bucket-level locking instead of locking the entire map, so
it’s faster than synchronized HashMap.
Example
import java.util.concurrent.ConcurrentHashMap;
System.out.println(map.get(1)); // Apple
}
}
1. What is a Servlet?
fi
• De nition: A Servlet is a Java class that runs on a web server and handles HTTP requests
and responses.
• It is part of Java EE (Jakarta EE) and is used to create dynamic web content.
• Extends HttpServlet class and overrides methods like doGet() and doPost(
1. init()
• Signature:
2. service()
• Determines the type of request (GET, POST, etc.) and calls doGet() or doPost().
• Signature:
3. destroy()
• Signature: