OOP Code Questions for the NSCT: Tracing Inheritance and Polymorphism

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

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

  1. Note two types for every call: the declared (static) type of the variable and the real (dynamic) type of the object.
  2. Compile time: find the methods visible in the declared type and pick the best-matching overload by argument types.
  3. Run time: if that method is overridable (any Java instance method, a C++ virtual function, any Python method), run the object's version of that exact signature.
  4. Fields and static methods do not dispatch. They are chosen by the declared type in Java and C++.
  5. For construction, go top-down. In Java the order is super constructor, then this class's field initialisers, then the constructor body.
  6. 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

Common mistakes

Practice set

  1. Python: class P has who() returning "P" and hi() returning "hi " + self.who(). class Q(P) overrides who() to return "Q". What does Q().hi() return?
  2. Python: B(A) defines its own __init__ that prints B and does not call super(). A's __init__ prints A. What does B() print?
  3. Python: class A has n = 0 and __init__ runs A.n += 1. After a, b, c = A(), A(), A(), what are A.n and a.n?
  4. Python: class V defines __add__ (adding x) and __eq__ (comparing x). What do (V(2) + V(3)).x, V(1) == V(1) and V(1) is V(1) give?
  5. Python: Base.run(self, n=1) returns "Base" * n, and Kid.run(self, n=2) returns super().run(n) + "!". What does Kid().run() return?
  6. Java: using the Parent and Child classes above, what does Parent q = new Parent(); q.m("hi"); print?
  7. C++: using Doc and Invoice above, what does Doc d = inv; d.title() return?
  8. Java: can a subclass override a private method of its parent?
  9. Which kind of polymorphism does method overloading provide?
Show answers
  1. "hi Q". self.who() dispatches to Q.
  2. B. The parent's __init__ is never called.
  3. 3 and 3. The counter is on the class, and a.n reads it.
  4. 5, True, False. Equal values, but different objects.
  5. "BaseBase!". Kid's default n = 2 is passed up the chain.
  6. P-Object. The object really is a Parent.
  7. "Doc". The copy is sliced to a Doc.
  8. No. A private method is not inherited, so a same-named method in the subclass is a new method, not an override.
  9. Compile-time (static) polymorphism. Overriding gives run-time polymorphism.

Practise: 20 questions

Interactive quiz loading. The first 10 questions are shown below.

  1. Does ColourPrinter override Printer's print method?

    class Printer {
        void print() { System.out.println("plain"); }
    }
    class ColourPrinter extends Printer {
        void print(String colour) { System.out.println(colour); }
    }
    1. No; print(String) has a different parameter list, so it overloads print() and both remain available
    2. Yes; any method with the same name in a subclass overrides the parent's
    3. No; the code fails to compile because the names clash
    4. Yes, but only when the call is made through a Printer reference
    Show answer

    Answer: A. No; print(String) has a different parameter list, so it overloads print() and both remain available

    Overriding needs the same name and the same parameter list (signature). print(String) differs from print(), so ColourPrinter inherits print() and adds an overload. A ColourPrinter object can call both print() and print("red").

  2. What happens when this code is compiled?

    class Animal { void eat() { System.out.println("eats"); } }
    class Dog extends Animal { void fetch() { System.out.println("fetches"); } }
    
    Animal a = new Dog();
    a.eat();     // line 1
    a.fetch();   // line 2
    1. Both lines compile, and line 2 prints fetches
    2. Line 1 fails, because a refers to a Dog
    3. It compiles, but line 2 throws ClassCastException at run time
    4. Line 2 fails to compile, because the declared type Animal has no fetch method
    Show answer

    Answer: D. Line 2 fails to compile, because the declared type Animal has no fetch method

    Java checks which methods may be called using the declared (static) type of the reference, here Animal. Animal has no fetch, so line 2 is a compile-time error even though the object is a Dog. A cast, ((Dog) a).fetch(), would compile and run.

  3. What does this C++ program print?

    #include <iostream>
    using namespace std;
    struct Base {
        void show() { cout << "Base "; }
        virtual void hello() { cout << "Hi-Base "; }
    };
    struct Derived : Base {
        void show() { cout << "Derived "; }
        void hello() override { cout << "Hi-Derived "; }
    };
    int main() {
        Derived d;
        Base& r = d;
        r.show();
        r.hello();
    }
    1. Base Hi-Derived
    2. Derived Hi-Derived
    3. Base Hi-Base
    4. Derived Hi-Base
    Show answer

    Answer: A. Base Hi-Derived

    show is not virtual, so the call is bound at compile time to the reference's static type, Base. hello is virtual, so the call is dispatched at run time to the object's real type, Derived. In C++, polymorphism through a reference or pointer needs virtual.

  4. What does this Python code print?

    class A:
        def hello(self):
            return "A"
    
    class B:
        def hello(self):
            return "B"
    
    class C(A, B):
        pass
    
    print(C().hello(), [k.__name__ for k in C.__mro__])
    1. B ['C', 'B', 'A', 'object']
    2. A ['C', 'A', 'B', 'object']
    3. A ['C', 'B', 'A', 'object']
    4. TypeError: ambiguous method hello
    Show answer

    Answer: B. A ['C', 'A', 'B', 'object']

    Python searches the method resolution order (MRO), which for class C(A, B) is C, A, B, object: left to right through the base list. A defines hello first, so 'A' is returned. Python does not report an ambiguity error the way C++ does.

  5. What does this Java code print?

    class A {
        static String who() { return "A"; }
        String me() { return "A"; }
    }
    class B extends A {
        static String who() { return "B"; }
        String me() { return "B"; }
    }
    A obj = new B();
    System.out.println(obj.who() + obj.me());
    1. BB
    2. AA
    3. BA
    4. AB
    Show answer

    Answer: D. AB

    Static methods are not overridden; B.who() only hides A.who(). A static call is resolved from the declared type, A, giving 'A'. Instance methods are overridden, so obj.me() dispatches to B and returns 'B'. The output is AB. Calling a static method through an instance compiles, but with a warning.

  6. Which line fails to compile, and why?

    class Parent {
        private int secret = 1;
        protected int shared = 2;
    }
    class Child extends Parent {
        int read1() { return shared; }   // line 1
        int read2() { return secret; }   // line 2
    }
    1. Line 1, because protected members are only visible in the same package
    2. Line 2, because a private member is not accessible in a subclass
    3. Both lines, because subclasses cannot read inherited fields
    4. Neither line; both fields are inherited
    Show answer

    Answer: B. Line 2, because a private member is not accessible in a subclass

    A protected member is accessible in subclasses, so line 1 compiles. A private member is accessible only inside the class that declares it, so line 2 fails even though the object physically contains secret. Parent would need a getter or a protected field.

  7. What does new SportsCar() print?

    class Vehicle {
        Vehicle() { System.out.print("Vehicle "); }
    }
    class Car extends Vehicle {
        int wheels = init();
        int init() { System.out.print("wheels "); return 4; }
        Car() { System.out.print("Car "); }
    }
    class SportsCar extends Car {
        SportsCar() { System.out.print("SportsCar"); }
    }
    // in main:
    new SportsCar();
    1. SportsCar Car wheels Vehicle
    2. wheels Vehicle Car SportsCar
    3. Vehicle wheels Car SportsCar
    4. Vehicle Car wheels SportsCar
    Show answer

    Answer: C. Vehicle wheels Car SportsCar

    Each constructor first calls super(), so Vehicle runs first. Before Car's constructor body runs, Car's field initialisers run, printing 'wheels'. Then the Car body runs, and finally the SportsCar body. Construction goes from the top of the hierarchy down.

  8. What does this Java code print?

    class Shape  { double area() { return 0; } }
    class Circle extends Shape {
        double r; Circle(double r) { this.r = r; }
        double area() { return 3 * r * r; }   // pi taken as 3
    }
    class Square extends Shape {
        double a; Square(double a) { this.a = a; }
        double area() { return a * a; }
    }
    // in main:
    Shape[] s = { new Circle(2), new Square(3), new Shape() };
    double total = 0;
    for (Shape x : s) total += x.area();
    System.out.println(total);
    1. 21.0
    2. 0.0
    3. 12.0
    4. 21
    Show answer

    Answer: A. 21.0

    Each call x.area() is dispatched on the real object: Circle gives 3 × 2 × 2 = 12, Square gives 3 × 3 = 9 and Shape gives 0. The total is 21. Because total is a double, println shows 21.0, not 21.

  9. Which overloads are chosen for Calc.f(5) and Calc.f(5.0f)?

    class Calc {
        static void f(long x)    { System.out.print("long "); }
        static void f(Integer x) { System.out.print("Integer "); }
        static void f(double x)  { System.out.print("double "); }
    }
    // in main:
    Calc.f(5);
    Calc.f(5.0f);
    1. Integer double
    2. long long
    3. double double
    4. long double
    Show answer

    Answer: D. long double

    Java picks overloads in phases. Phase 1 allows only identity and primitive widening, and it beats boxing. For 5 (an int), both long and double qualify by widening, and the most specific, long, wins over Integer. For 5.0f (a float), only double is reachable by widening.

  10. What does this Python code print?

    class Counter:
        count = 0
        def hit(self):
            self.count += 1
    
    a, b = Counter(), Counter()
    a.hit(); a.hit(); b.hit()
    Counter.count = 10
    print(a.count, b.count, Counter().count)
    1. 2 1 10
    2. 10 10 10
    3. 3 3 10
    4. 12 11 10
    Show answer

    Answer: A. 2 1 10

    self.count += 1 reads the class attribute the first time, then creates an instance attribute that shadows it. So a.count becomes 2 and b.count becomes 1, both stored on the instances. Changing Counter.count to 10 affects only objects without their own count, such as a new Counter().

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.