OOPs Concepts in Java

🔷 What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”. These objects can contain data (fields or attributes) and code (methods or functions). Java is a pure object-oriented language (except for primitive types like int, char, etc.).

OOP focuses on organizing code using objects, making it modular, reusable, and easier to debug or maintain.


🔷 Four Main Pillars of OOP in Java

1. Encapsulation

  • Wrapping data and code together into a single unit (class).

  • Data is hidden using private access modifiers, and access is provided through getters/setters.

  • Ensures data security and prevents direct modification.

📘 Example:

public class Student {
private String name;

public void setName(String n) {
name = n;
}

public String getName() {
return name;
}
}

2. Inheritance

  • Allows a class to inherit properties and methods from another class.

  • Promotes code reuse and hierarchical classification.

📘 Example:

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}

3. Polymorphism

  • Means “many forms”. Java allows methods to behave differently based on the context.

  • Compile-time polymorphism: Method overloading

  • Runtime polymorphism: Method overriding

📘 Example:

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}

4. Abstraction

  • Hiding internal implementation and showing only essential features.

  • Achieved using abstract classes and interfaces.

📘 Example:

abstract class Shape {
abstract void draw();
}

class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}


🔷 Benefits of OOP

  • 🔁 Reusability through inheritance

  • 🧩 Modular structure

  • 🔒 Security through encapsulation

  • 🚀 Easier to scale and maintain

  • 📚 More realistic program design

Related Posts