← Chapter 6 — Object-Oriented Programming

23. OOP Principles

mixed

Description

Object-oriented programming organizes code around objects and their responsibilities. Its four commonly taught ideas are encapsulation, inheritance, polymorphism, and abstraction.

These are design tools, not rules to force into every class. Use them when they make code safer, clearer, or easier to extend.

The four foundational object-oriented programming concepts.
The four foundational object-oriented programming concepts.

Subtopics

Encapsulation

Description

Keep data and its rules together.

Explanation

Private fields with public methods protect valid object state.

Example

private int score;

Abstraction

Description

Expose useful behavior and hide unnecessary detail.

Explanation

A caller can use a method without knowing its internal steps.

Example

student.study();

Explanation

Inheritance lets a child class reuse a parent contract, and polymorphism lets code use a parent type while different child behavior runs. Favor simple composition when inheritance does not represent a true "is a" relationship.

Example

public class OopPrinciplesDemo {
    static class Student {
        private int score;
        void setScore(int score) { this.score = score; }
        int getScore() { return score; }
    }

    public static void main(String[] args) {
        Student rohan = new Student();
        rohan.setScore(88);
        System.out.println(rohan.getScore());
    }
}

Key points

  • Encapsulation protects state.
  • Inheritance models an is-a relationship.
  • Polymorphism supports interchangeable behavior.

Video

Open video

Open reference