OOPs Principles

1. Encapsulation"Data hiding"

  • Binding data (variables) and methods (functions) together in a class.
  • Keeps the internal state safe from outside interference.

✅ Achieved using private variables and public getter/setter methods.

class Student {
    private String name;

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

    public String getName() {
        return name;
    }
}


2. Abstraction"Show only what’s needed"

  • Hides complex implementation and shows only essential features.
  • Focus on what an object does, not how it does it.

✅ Achieved using abstract classes and interfaces.

interface Animal {
    void makeSound(); // abstract method
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}


3. Inheritance"Code reuse"

  • One class (child) inherits properties and methods from another class (parent).
  • Promotes code reusability and hierarchy.

✅ Use the extends keyword.

class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

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


4. Polymorphism"Many forms"

  • Ability to take many forms: same method behaves differently in different classes.
  • Two types: Compile-time (method overloading) and Run-time (method overriding)

// Method Overloading (compile-time)
class Math {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}

// Method Overriding (run-time)
class Animal {
    void sound() { System.out.println("Some sound"); }
}
class Cat extends Animal {
    void sound() { System.out.println("Meow"); }
}


🔚 In Short:

Principle Purpose
Encapsulation Protect data
Abstraction Hide complexity
Inheritance Reuse code
Polymorphism One method, many forms

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.