Back to Study Material Java

OOP Concepts in Java

Object-Oriented Programming (OOP) is a programming paradigm that organizes software around objects—self-contained units that combine data (fields) and be...

OOP Concepts in Java

The Four Pillars of Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that organizes software around objects—self-contained units that combine data (fields) and behavior (methods). Java was built from the ground up as an object-oriented language, and understanding OOP principles is essential to writing clean, maintainable Java code. The four foundational pillars are encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation: Hiding Internal Details Encapsulation means bundling related data and the methods that operate on that data into a single class, then controlling access through visibility modifiers. Fields are typically declared private, and access is granted through public getter and setter methods. This protects the internal state from unintended external modification and lets you change the implementation without affecting code that uses the class.

Inheritance: Reusing and Extending Behavior Inheritance allows one class to acquire the fields and methods of another. The subclass (child) extends the superclass (parent) using the extends keyword. This models an "is-a" relationship: a Dog is an Animal, so Dog can extend Animal and inherit its breathe() and eat() methods while adding its own bark() method. Inheritance promotes code reuse but should be used thoughtfully; deep inheritance hierarchies become hard to follow.

Polymorphism and Abstraction Polymorphism means one interface can refer to objects of many different types. A variable of type Animal can hold a Dog or a Cat, and calling speak() on it invokes the correct version at runtime. Abstraction hides complex implementation details behind a simple interface. Abstract classes and interfaces are the primary tools for abstraction in Java, letting callers work with a concept without knowing the underlying mechanics.

Code Example: abstract class Shape { abstract double area(); } class Circle extends Shape { double r; Circle(double r) { this.r = r; } double area() { return Math.PI * r * r; } } Shape s = new Circle(5); System.out.println(s.area()); // 78.53...

Interview Tip: When asked to explain OOP, give a concrete real-world analogy for each pillar. For example, encapsulation is like a capsule that hides the medicine inside; you interact with it through a defined interface without needing to know the chemical formula. Concrete analogies demonstrate genuine understanding rather than memorized definitions.