What are OOP Concepts in Java?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which contain data (variables) and behavior (methods). It helps in writing modular, reusable, and maintainable code.
The four main pillars of OOP are:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
1. Encapsulation
Definition:
Encapsulation is the process of wrapping data (variables) and code (methods) together into a single unit and restricting direct access to some components.
Real-Time Example:
A capsule (medicine) contains different ingredients inside but hides its internal details.
Java Example:
class Employee {
private int salary;
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Key Points:
- Use
privatevariables - Access via getters/setters
- Improves security
2. Inheritance
Definition:
Inheritance allows one class to acquire the properties and behavior of another class.
Real-Time Example:
A child inherits properties from parents.
Java Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
Key Points:
- Promotes code reusability
- Uses
extendskeyword
3. Polymorphism
Definition:
Polymorphism means “many forms”. It allows methods to perform different tasks based on input.
Types:
- Compile-time (Method Overloading)
- Runtime (Method Overriding)
Java Example (Overloading):
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Java Example (Overriding):
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Key Points:
- Same method name, different behavior
- Improves flexibility
4. Abstraction
Definition:
Abstraction means hiding implementation details and showing only essential features.
Real-Time Example:
When you drive a car, you only use steering, brake, and accelerator without knowing internal engine details.
Java Example:
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with key");
}
}
Key Points:
- Achieved using abstract classes and interfaces
- Focuses on “what” rather than “how”
Conclusion
OOP concepts help developers to:
- Write clean and maintainable code
- Improve code reusability
- Enhance security and flexibility
Interview Tip:
Always explain OOP concepts with:
✔ Definition
✔ Real-life example
✔ Java code