T TestsWorld
← All topic guides

OOP Principles: formulas, shortcuts & solved examples

What it is

Object-oriented programming (OOP) organises code around objects that bundle data (fields) with behaviour (methods). Four principles appear in almost every campus interview and online assessment: encapsulation, abstraction, inheritance and polymorphism. Questions test both definitions and the output of short programs.

Key rules

The four pillars

  • Encapsulation: keep data private and expose it only through methods. It protects invariants, such as a bank balance never going negative.
  • Abstraction: show what an object does, hide how. Abstract classes and interfaces are the tools.
  • Inheritance: a child class reuses and extends a parent class. It models an "is-a" relationship (a SavingsAccount is an Account).
  • Polymorphism: one interface, many forms.
    • Compile-time (static): method overloading, same name with different parameter lists.
    • Run-time (dynamic): method overriding, where the call is resolved by the object's actual type.

Rules that decide outputs

  1. With overriding, the object type (not the reference type) decides which method runs.
  2. Constructors run parent first, then child in Java and C++. In Python, the parent __init__ runs only if you call super().__init__().
  3. Static (class-level) variables are shared by all instances.
  4. Overloading is resolved at compile time; return type alone cannot distinguish two overloads.
  5. Java does not allow multiple inheritance of classes, but a class may implement many interfaces. C++ and Python allow multiple inheritance; Python resolves it using the Method Resolution Order (MRO).

Composition versus inheritance

Use inheritance for "is-a" and composition for "has-a". A Car has an Engine; it is not an Engine. Many design questions reward preferring composition.

Shortcuts

  1. "Which method runs?" Look at what was created with new (or the constructor call), then walk up the hierarchy until you find the method.
  2. Diamond in Python. For class D(B, C) where both extend A, the MRO is D, B, C, A. Each super() call moves to the next class in that list, not necessarily the direct parent.
  3. Keyword mapping. private / getters / setters means encapsulation; abstract / interface means abstraction; extends means inheritance; same name, different behaviour means polymorphism.

Solved examples

Example 1: Run-time polymorphism

class Account:
    count = 0
    def __init__(self, bal):
        self._bal = bal
        Account.count += 1
    def interest(self):
        return self._bal * 0.04

class Savings(Account):
    def interest(self):
        return self._bal * 0.07

class FD(Account):
    def interest(self):
        return super().interest() + 500

for a in [Account(10000), Savings(10000), FD(10000)]:
    print(type(a).__name__, round(a.interest()))
print(Account.count)

Solution. Account gives 10000 × 0.04 = 400. Savings overrides: 700. FD calls the parent version (400) and adds 500: 900. All three constructors increment the shared class variable, so count is 3.

Output:

Account 400
Savings 700
FD 900
3

Example 2: Constructor chaining

class P:
    def __init__(self):
        print("P init")

class Q(P):
    def __init__(self):
        print("Q init")
        super().__init__()

Q()

Solution. Python runs Q's __init__ first, which prints "Q init", then explicitly calls the parent: "P init". In Java, the equivalent code would print the parent line first, because super() must be the first statement of a constructor.

Example 3: Diamond inheritance

class A:
    def hi(self): return "A"
class B(A):
    def hi(self): return "B" + super().hi()
class C(A):
    def hi(self): return "C" + super().hi()
class D(B, C):
    pass

print(D().hi())

Solution. The MRO of D is D, B, C, A. D has no hi, so B's runs and returns "B" plus the next in the MRO, which is C, not A. C returns "C" + A's "A". Output: BCA.

Example 4: Overloading versus overriding (Java)

class Calc {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b + 0.5; }
}
// new Calc().add(2, 3) and new Calc().add(2.0, 3.0)

Solution. The compiler picks the overload by argument types. add(2, 3) matches the int version and gives 5; add(2.0, 3.0) matches the double version and gives 5.5. This is compile-time polymorphism. No inheritance is involved, so it is not overriding.

Common mistakes

  1. Confusing abstraction with encapsulation. Abstraction is about hiding complexity at the design level; encapsulation is about restricting access to data.
  2. Assuming the reference type decides the call. In Account a = new Savings(), a.interest() runs the Savings version.
  3. Thinking return type alone allows overloading. Two methods differing only in return type will not compile in Java.
  4. Forgetting super().__init__() in Python. The parent's fields are then never set, causing an AttributeError later.
  5. Overusing inheritance. Making Employee extend Department to "reuse code" breaks the is-a rule; use composition instead.

Practice now: https://www.testsworld.com/mocks

Ready to practise OOP Principles?
Take a free mock test

Related guides