Java is a pure object-oriented language (except for primitive data types). Understanding OOP is non-negotiable for interviews and real-world coding.
1. What is OOP?
OOP (Object-Oriented Programming) is a programming paradigm based on the concept of objects.
- Objects = instances of classes.
- Classes define data (fields/variables) + behavior (methods/functions).
- OOP makes code modular, reusable, and easy to maintain.
🔑 Benefits of OOP in Java:
- Reusability → use inheritance to avoid rewriting code.
- Modularity → divide big problems into objects.
- Security → encapsulation hides sensitive details.
- Flexibility → polymorphism allows dynamic behavior.
The 4 Pillars of OOP:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
2. Classes and Objects
Class → Blueprint/Template
Defines how objects should look and behave.
class Student {
String name;
int age;
void study() {
System.out.println(name + " is studying.");
}
}
Object → Instance of Class
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Object creation
s1.name = "Rahul";
s1.age = 21;
s1.study(); // Output: Rahul is studying.
}
}
📌 Interview Note:
- Class = logical entity, doesn’t consume memory until instantiated.
- Object = physical instance, consumes memory in heap.
3. Constructors
Special method called when an object is created.
- Same name as class.
- No return type.
Types:
- Default Constructor – created automatically if not defined.
- Parameterized Constructor – takes arguments.
- Constructor Overloading – multiple constructors with different parameters.
class Student {
String name;
int age;
// Default Constructor
Student() {
name = "Unknown";
age = 18;
}
// Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}
}
📌 Interview Notes:
- Can a constructor be final, abstract, static? → NO.
- Why? Because constructors are meant to initialize objects, not to be inherited, overridden, or shared.
4. this and super
this → Refers to the current object.
class Student {
String name;
Student(String name) {
this.name = name; // differentiate between local & instance variable
}
}
super → Refers to the parent class.
class Animal {
String type = "Animal";
}
class Dog extends Animal {
String type = "Dog";
void printTypes() {
System.out.println(this.type); // Dog
System.out.println(super.type); // Animal
}
}
📌 Interview Tip:
this()→ calls another constructor of same class.super()→ calls parent class constructor (must be first line).
5. Static Members
- Static variables → shared across all objects.
- Static methods → belong to class, can be called without object.
- Static blocks → run once when class loads.
class Counter {
static int count = 0; // shared across objects
Counter() { count++; }
static void displayCount() {
System.out.println("Objects created: " + count);
}
}
📌 Interview Notes:
- Static methods cannot use non-static variables (because non-static requires an object).
- Commonly used for utility classes (e.g.,
Math.sqrt()).
6. Encapsulation
Definition: Binding data and methods together, hiding implementation details.
-
Use
privatevariables. - Provide
publicgetters and setters.
class BankAccount {
private double balance;
public void deposit(double amount) {
if(amount > 0) balance += amount;
}
public double getBalance() {
return balance;
}
}
📌 Why Encapsulation?
- Security: Prevents unauthorized access.
- Control: Validation before updating values.
- Maintainability: Class internals can change without affecting outside code.
7. Inheritance
Definition: Mechanism where a class (child) inherits fields & methods of another class (parent).
class Vehicle {
void move() { System.out.println("Vehicle is moving"); }
}
class Car extends Vehicle {
void honk() { System.out.println("Car honks!"); }
}
📌 Types of Inheritance in Java:
- Single → one parent, one child.
- Multilevel → grandparent → parent → child.
- Hierarchical → one parent, multiple children.
- Multiple inheritance with classes is NOT allowed (diamond problem). Use interfaces instead.
8. Polymorphism
Definition: Ability of an object to take many forms.
1. Compile-time (Method Overloading)
Same method name, different parameter list.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
2. Runtime (Method Overriding)
Child class provides its own implementation of a parent method.
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Bark"); }
}
📌 Interview Notes:
- Overloading = compile-time binding.
- Overriding = runtime binding (dynamic dispatch).
@Overrideannotation → prevents mistakes.
9. Abstraction
Definition: Hiding implementation details, exposing only functionality.
Using Abstract Class
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
}
Using Interfaces
interface Flyable {
void fly();
}
class Bird implements Flyable {
public void fly() { System.out.println("Bird is flying"); }
}
📌 Differences: Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have abstract & concrete | Only abstract (Java 7), default & static (Java 8+) |
| Variables | Can have variables | All variables are public static final |
| Multiple Inheritance | Not supported | Supported |
| Use Case | "IS-A" relationships with base logic | Common behavior contracts |
10. Access Modifiers
- public → accessible everywhere.
- protected → accessible in same package + subclasses.
- default (no keyword) → accessible within package.
- private → accessible only within class.
📌 Interview Tip:
-
Fields → usually
private. - Methods →
public(to expose behavior).
11. Real-World Example (All OOP in one)
abstract class Employee { // Abstraction
String name;
int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
abstract double calculateSalary(); // Abstract Method
}
class Developer extends Employee {
double hourlyRate;
int hoursWorked;
Developer(String name, int id, double rate, int hours) {
super(name, id);
this.hourlyRate = rate;
this.hoursWorked = hours;
}
@Override
double calculateSalary() { // Polymorphism (Overriding)
return hourlyRate * hoursWorked;
}
}
class Manager extends Employee {
double baseSalary;
Manager(String name, int id, double salary) {
super(name, id);
this.baseSalary = salary;
}
@Override
double calculateSalary() {
return baseSalary;
}
}
public class Main {
public static void main(String[] args) {
Employee e1 = new Developer("Alice", 101, 50, 160);
Employee e2 = new Manager("Bob", 102, 8000);
System.out.println(e1.name + " Salary: " + e1.calculateSalary());
System.out.println(e2.name + " Salary: " + e2.calculateSalary());
}
}
12. OOP Interview Questions
- What are the 4 pillars of OOP? Explain with examples.
- Difference between abstract class and interface?
- Why are Strings immutable in Java?
- Can constructors be inherited? (No)
- Difference between overloading and overriding?
- Can we override static methods? (No – static methods are bound at compile time)
- Difference between
thisandsuper. - Why Java doesn’t support multiple inheritance with classes?
Summary (Memory Hooks)
- Encapsulation → Data hiding →
private + getters/setters. - Inheritance → Code reuse →
extends. - Polymorphism → Many forms → overloading/overriding.
- Abstraction → Hide implementation →
abstract/interface.
If you master these with code examples + interview reasoning, you can handle 90% of OOP interview questions.
Next Chapter: Inheritance & Polymorphism