Explain the four pillars of OOP with Java examples.
Answer
- Encapsulation: hide data (
private fields) and expose behavior through methods, so the class controls its own rules. - Inheritance: a class reuses and extends another (
class Dog extends Animal). Prefer composition when it is not a true "is-a". - Polymorphism: the same call behaves differently depending on the real object:
Animal a = new Dog(); a.speak(); runs Dog's version. - Abstraction: expose what something does, hide how: interfaces and abstract classes (
List vs ArrayList). - Interview tip: give one tiny example for each and say when inheritance is a bad idea.
Practice this question in Repaso