OOP Code Questions for the NSCT: Tracing Inheritance and Polymorphism
OOP code questions show a short class hierarchy in Java, C++ or Python and ask what it prints, which method runs or which line fails to compile. Almost all of them test two decisions. The first is which method signature the compiler picks, based on the declared type. The second is which implementation runs, based on the object's real type. Programming carries 10% of the NSCT according to HEC's Areas of Competencies, and candidates averaged 47.8% accuracy in it in 2026, per the HEC NSCT report.
The official Object-Oriented Programming topic defines the four pillars. This page traces code. The Python examples were run directly. No compiler was available for Java or C++, so each of those was traced line by line and the rules were mirrored in a Python model.
The method, step by step
- Note two types for every call: the declared (static) type of the variable and the real (dynamic) type of the object.
- Compile time: find the methods visible in the declared type and pick the best-matching overload by argument types.
- Run time: if that method is overridable (any Java instance method, a C++
virtualfunction, any Python method), run the object's version of that exact signature. - Fields and static methods do not dispatch. They are chosen by the declared type in Java and C++.
- For construction, go top-down. In Java the order is super constructor, then this class's field initialisers, then the constructor body.
- Write the output token by token as you go, including spaces and newlines.
Inheritance and constructor order
Worked example (Python).
class Account:
def __init__(self, owner):
print("Account init")
self.owner = owner
def fee(self):
return 100
def describe(self):
return f"{self.owner}: fee {self.fee()}"
class Savings(Account):
def __init__(self, owner, rate):
super().__init__(owner)
print("Savings init")
self.rate = rate
def fee(self):
return 0
for a in [Account("Ali"), Savings("Sara", 5)]:
print(a.describe())
Output:
Account init
Account init
Savings init
Ali: fee 100
Sara: fee 0
Both objects are built before the loop. describe is inherited, but self.fee() inside it dispatches on the real object, so Sara's line uses Savings.fee. Python never calls the parent's __init__ automatically. Remove the super().__init__(owner) line and self.owner is never set.
Worked example (Java, traced). Here this(...) calls another constructor in the same class:
class X { X() { System.out.print("X "); } }
class Y extends X {
Y() { this(5); System.out.print("Y"); }
Y(int n) { System.out.print(n + " "); } // implicit super() first
}
// new Y() prints: X 5 Y
Y() delegates to Y(int). That constructor implicitly calls super(), which prints X, and then prints 5. Control returns to Y(), which prints Y. A constructor can call this(...) or super(...), but not both, and the call must be its first statement.
Polymorphism and dynamic dispatch
Polymorphism means one call site runs different code depending on the object. In Java and Python every instance method is overridable. In C++ only virtual functions are.
Worked example (C++, traced).
struct Doc {
virtual string title() { return "Doc"; }
string code() { return "D0"; }
};
struct Invoice : Doc {
string title() override { return "Invoice"; }
string code() { return "I9"; }
};
Invoice inv;
Doc* p = &inv;
Invoice* q = &inv;
| Call | title() (virtual) | code() (non-virtual) |
|---|---|---|
p-> (declared Doc*) |
Invoice | D0 |
q-> (declared Invoice*) |
Invoice | I9 |
The virtual call follows the object. The non-virtual call follows the pointer's declared type. Also note that passing inv by value to a Doc parameter copies only the Doc part (object slicing), so even title() returns "Doc" there.
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| Signature | Same name, different parameters | Same name and parameters |
| Where | Same class, or added in a subclass | Subclass replaces the parent's version |
| Decided | Compile time (declared types) | Run time (object type) |
| Python | Not supported; a later def replaces an earlier one |
Supported |
Worked example (Java two-step, traced).
class Parent { void m(Object o) { System.out.println("P-Object"); } }
class Child extends Parent {
void m(Object o) { System.out.println("C-Object"); }
void m(String s) { System.out.println("C-String"); }
}
Parent p = new Child();
p.m("hi"); // C-Object
new Child().m("hi"); // C-String
For p.m("hi"), the compiler sees only Parent's methods, so it fixes the signature m(Object). At run time the object is a Child, so Child's m(Object) runs and prints C-Object. The better-matching m(String) is never considered, because Parent does not declare it. Through a Child reference, the compiler can see m(String) and picks it.
Worked example (Python "overloading").
class Calc:
def add(self, a, b):
return a + b
def add(self, a, b, c=0):
return a + b + c
c = Calc()
print(c.add(2, 3), c.add(2, 3, 4)) # 5 9
The second def replaces the first. Default arguments, *args or functools.singledispatchmethod give overload-like behaviour.
Abstract classes
An abstract class cannot be instantiated. With from abc import ABC, abstractmethod, a subclass Sq that implements area works (Sq(4).area() returns 16), but Shape() raises TypeError: Can't instantiate abstract class Shape.... In Java, new Shape() on an abstract class is a compile-time error. In C++, any class with a pure virtual function (= 0) is abstract.
Speed tricks
- Circle the declared type and the object type on every call before reading any method body.
- Java fields, static methods and overload choice follow the declared type. Instance method bodies follow the object.
- In C++, look for
virtualfirst. Without it, the pointer type decides. - Constructors print top-down. C++ destructors print bottom-up, in reverse order of construction.
- In Python, print
Class.__mro__mentally for multiple inheritance.super()follows that list.
Common mistakes
- Assuming a better overload in the subclass is used through a superclass reference.
- Expecting
virtualbehaviour in C++ when the method is not declaredvirtual. - Thinking a Java overridden method called from a superclass constructor sees initialised subclass fields. It sees default values.
- Writing
equals(Point p)in Java instead of overridingequals(Object o). - Defining a mutable list as a Python class attribute and expecting one copy per object.
- Passing objects by value in C++ and losing the derived part to slicing.
Practice set
- Python:
class Phaswho()returning "P" andhi()returning"hi " + self.who().class Q(P)overrideswho()to return "Q". What doesQ().hi()return? - Python:
B(A)defines its own__init__that prints B and does not callsuper(). A's__init__prints A. What doesB()print? - Python:
class Ahasn = 0and__init__runsA.n += 1. Aftera, b, c = A(), A(), A(), what areA.nanda.n? - Python: class V defines
__add__(adding x) and__eq__(comparing x). What do(V(2) + V(3)).x,V(1) == V(1)andV(1) is V(1)give? - Python:
Base.run(self, n=1)returns"Base" * n, andKid.run(self, n=2)returnssuper().run(n) + "!". What doesKid().run()return? - Java: using the Parent and Child classes above, what does
Parent q = new Parent(); q.m("hi");print? - C++: using Doc and Invoice above, what does
Doc d = inv; d.title()return? - Java: can a subclass override a
privatemethod of its parent? - Which kind of polymorphism does method overloading provide?
Show answers
- "hi Q". self.who() dispatches to Q.
- B. The parent's
__init__is never called. - 3 and 3. The counter is on the class, and
a.nreads it. - 5, True, False. Equal values, but different objects.
- "BaseBase!". Kid's default n = 2 is passed up the chain.
- P-Object. The object really is a Parent.
- "Doc". The copy is sliced to a Doc.
- No. A private method is not inherited, so a same-named method in the subclass is a new method, not an override.
- Compile-time (static) polymorphism. Overriding gives run-time polymorphism.
Practise: 20 questions
FAQs
Why does Java choose the overload by declared type but the body by object type?
Overload resolution happens when the code is compiled, and the compiler only knows declared types. Method bodies are bound when the program runs, through the object's method table (vtable), so the real object decides. Keeping these two steps separate explains nearly every tricky Java output question.
Is Python method resolution the same as Java's?
Partly. Every Python method is overridable, like Java's instance methods. But Python has no compile-time overload selection: one name maps to one function, chosen by looking up the instance, its class and then the MRO at call time. For multiple inheritance, Python's C3 linearisation decides the order.
What is the difference between hiding and overriding?
Overriding replaces an instance method, and calls dispatch on the object's type. Hiding happens with static methods and fields: the subclass declares a member with the same name, but which one you get depends on the declared type of the reference. Java fields and static methods hide; they never override.
Does C++ call virtual functions virtually inside a constructor?
No, not to a more-derived version. While the base constructor runs, the object's dynamic type is still the base, so a virtual call inside it runs the base version. Java differs: it dispatches to the subclass override even during the base constructor, which is why uninitialised subclass fields show default values.
Next step
Go back to the official OOP topic, then try pointers and memory practice for C++ object lifetimes. See every topic on the Programming MCQs hub, or take an NSCT mock test.