Four Pillars of OOP in Java
1. Encapsulation
Encapsulation is the process of bundling data (attributes) and methods (functions)
that operate on that data into a single unit, typically a class. It restricts direct access to some of
the object's components to maintain control over the internal state.
Example:
class Person {
private String name; // private variable
// Getter method
public String getName() {
return name;
// Setter method
public void setName(String name) {
this.name = name;
2. Abstraction
Abstraction is the concept of hiding the complex implementation details and exposing
only the essential features of an object. This allows a focus on what an object does rather than how
it does it.
Example:
abstract class Animal {
abstract void sound(); // Abstract method
class Dog extends Animal {
void sound() {
System.out.println("Bark");
3. Inheritance
Inheritance allows a class (child class) to inherit fields and methods from another class
(parent class). It promotes code reusability and establishes a natural hierarchy.
Example:
class Animal {
void eat() {
System.out.println("Eating");
class Dog extends Animal {
void bark() {
System.out.println("Barking");
4. Polymorphism
Polymorphism enables a single interface to represent different types of objects,
allowing methods to perform different actions based on the object they are acting upon.
Method Overloading Example:
class MathOperation {
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
Method Overriding Example:
class Animal {
void sound() {
System.out.println("Animal sound");
class Dog extends Animal {
void sound() {
System.out.println("Bark");