Skip to the page

Object-oriented programming · core

The four pillars and encapsulation

Encapsulation, abstraction, inheritance and polymorphism are four ideas. You must show each in code, not only name it.

The notes

What you must know

  • Encapsulation: data is private and changed only through methods that check it. A private balance with a deposit method that rejects a negative amount.
  • Abstraction: show what something does, hide how. A base type says every account has an interest rate without saying how it is calculated.
  • Inheritance: a child class reuses and extends a parent (SavingsAccount extends Account).
  • Polymorphism: the same call runs different code by the actual object type, chosen at runtime (method overriding).
  • An abstract class cannot be created with new.
  • Marks set to minus fifty: make the field private and change it only through a method that checks the range and throws an error with a clear message. Check in the constructor too.
  • Java access: private (same class), default (same package), protected (same package plus subclasses), public (everyone).
  • Not every field needs a setter. The roll number can be final and set once in the constructor.

The red pen

Common traps: mistake → fix

  • Mistake: Abstraction and encapsulation are the same

    Fix: abstraction hides how; encapsulation protects data.

  • Mistake: Generate getters and setters for everything

    Fix: a setter without a check gives no protection.

  • Mistake: protected means only subclasses

    Fix: in Java the same package can also see it.

  • Mistake: Validate only in the web form

    Fix: other code can still set a bad value.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain the four pillars with an example from code.
  2. Marks are sometimes set to -50. How do you stop it?
  3. What are the access modifiers in Java?
  4. What is the difference between abstraction and encapsulation?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview