Autocoder

Inheritance and Polymorphism Interview Questions

Last updated 2026-11-19

Inheritance and polymorphism questions are mostly about prediction: given a few lines of code, what prints, and why? This page gives the rules behind those puzzles and works through the classic ones, including constructor order, hidden fields, static methods and Python's method resolution order.

It deepens the basics from OOPs interview questions. Pair it with abstraction and encapsulation and the Liskov principle in SOLID questions. The preparation plan is in how to crack an OOPs interview.

LanguagesJava, Python, C++
StyleOutput prediction and rule explanation
LevelMedium to hard

Rules to know before the puzzles

Inheritance and Polymorphism Interview Questions: questions with worked answers

  1. 1

    What are the types of inheritance?

    easy

    Single: one parent, one child. Multilevel: a chain A to B to C. Hierarchical: several children of one parent. Multiple: a child with several parents, supported for classes in C++ and Python but not in Java, which allows multiple interface implementation instead. Hybrid combines these. Choose a shallow hierarchy; deep chains make behaviour hard to follow.

  2. 2

    What does this print: a field and a method accessed through a parent reference?

    medium

    Fields are not polymorphic. With A x = new B(), x.name uses the declared type A, so it prints A. Instance method x.who() dispatches on the object's class, so B runs. The static method x.s() is bound to the declared type, so sA prints. Output: A, B, sA. The static method is hidden, not overridden.

    java
    class A { String name = "A"; String who() { return "A"; } static String s() { return "sA"; } }
    class B extends A { String name = "B"; String who() { return "B"; } static String s() { return "sB"; } }
    A x = new B();
    System.out.println(x.name + " " + x.who() + " " + x.s());   // A B sA
  3. 3

    What is the output when a parent constructor calls an overridden method?

    hard

    new C() runs P's constructor first, which prints P and calls init(). Dispatch is dynamic, so C.init runs even though C's constructor body has not started and its field initialisers have not yet run; v still has the default value 0. Output: P, then C.init v=0, then C. The lesson: never call overridable methods from a constructor, because they can observe a half-built object.

    java
    class P { P() { System.out.println("P"); init(); } void init() { System.out.println("P.init"); } }
    class C extends P {
        int v = 5;
        C() { System.out.println("C"); }
        @Override void init() { System.out.println("C.init v=" + v); }
    }
    new C();   // P / C.init v=0 / C
  4. 4

    What are the rules for overriding a method in Java?

    medium

    The name and parameter types must match. The return type must be the same or a covariant subtype. Visibility may be widened but not narrowed, so a public method cannot become protected. A checked exception may be narrowed or dropped but not broadened. final, private and static methods cannot be overridden (static ones are hidden). Use @Override so the compiler catches signature mistakes.

  5. 5

    How does overload resolution work, and what does print(null) do?

    medium

    The compiler selects the most specific applicable overload using the declared argument types: exact match first, then widening primitives, then boxing, then varargs. With print(Object) and print(String) both present, print(null) picks String because it is more specific. If the candidates were String and Integer, the call is ambiguous and does not compile. A call on an int argument prefers print(long) over print(Integer) because widening beats boxing.

  6. 6

    What are upcasting and downcasting, and when does ClassCastException occur?

    medium

    Upcasting treats a subclass object as its superclass and is implicit and always safe: Animal a = new Dog(). Downcasting goes back to the subclass and needs an explicit cast, which the JVM checks at run time. If the actual object is not an instance of the target type, a ClassCastException is thrown. Guard with instanceof, and in modern Java use pattern matching: if (a instanceof Dog d) { d.bark(); }. Frequent downcasts suggest the design should use polymorphism instead.

  7. 7

    Explain Python's method resolution order with the diamond.

    hard

    Python linearises the class hierarchy with the C3 algorithm so each class appears before its parents and the order of listed bases is respected. For class D(B, C) where B and C both extend A, D.__mro__ is D, B, C, A, object. super() follows this order, not simply the immediate parent, which is what makes cooperative multiple inheritance work. If both B and C define greet and call super().greet(), A's runs once.

    python
    class A:
        def greet(self): print("A")
    class B(A):
        def greet(self): print("B"); super().greet()
    class C(A):
        def greet(self): print("C"); super().greet()
    class D(B, C): pass
    D().greet()            # B C A
    print([k.__name__ for k in D.__mro__])   # ['D', 'B', 'C', 'A', 'object']
  8. 8

    What is the Liskov substitution principle? Show a violation.

    medium

    Objects of a subclass must be usable wherever the superclass is expected without breaking the program's correctness. The classic violation is Square extending Rectangle: code that sets width to 5 and height to 4 expects area 20, but a Square that keeps sides equal returns 16. The subclass strengthened an invariant. Fix by not inheriting, using separate classes under a Shape interface. Signs of violation include overrides that throw UnsupportedOperationException or tighten preconditions. See SOLID questions.

  9. 9

    What does super do, and how does constructor chaining work?

    medium

    super refers to the parent part of the object. super(args) must be the first statement in a constructor and chooses which parent constructor runs; if omitted, the compiler inserts super() and fails if the parent has no no-argument constructor. super.method() calls the parent's version of an overridden method. The order for new Child() is: parent constructors from the top of the hierarchy down, with field initialisers of each class run just before that class's constructor body.

  10. 10

    Why does C++ need virtual destructors?

    hard

    If you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs, which is undefined behaviour and leaks the derived part's resources. Declaring the base destructor virtual makes the delete dispatch to the most derived destructor first, then base destructors in order. Rule: any class meant to be used polymorphically gets a public virtual destructor, or a protected non-virtual one if deletion through the base is forbidden.

    cpp
    struct Base { virtual ~Base() { puts("~Base"); } };
    struct Derived : Base { ~Derived() override { puts("~Derived"); } };
    Base* p = new Derived;
    delete p;   // ~Derived then ~Base
  11. 11

    Compile-time versus run-time polymorphism: examples and costs.

    medium

    Compile-time polymorphism resolves the call during compilation: method overloading, operator overloading in C++, and templates or generics. It has no run-time cost. Run-time polymorphism resolves through virtual dispatch based on the object's actual type, costing one indirect call and blocking some inlining. It enables plug-in designs, such as a list of Shape objects each computing its own area. In C++ it needs virtual functions; in Java every non-static, non-private, non-final method is virtual.

  12. 12

    Can you override a private or static method?

    medium

    No. A private method is not visible to subclasses, so a subclass method with the same signature is a new, unrelated method. A static method belongs to the class; defining the same static method in a subclass hides the parent's, and the call is resolved by the declared type at compile time. Neither participates in dynamic dispatch. In Python a name-mangled __method is likewise not overridden by a subclass's __method.

  13. 13

    How should you design with inheritance without causing the fragile base class problem?

    medium

    Keep the parent small and stable, document which methods are meant to be overridden, make everything else final, and avoid calling overridable methods from the parent's own methods, since subclasses may depend on that internal call order. Prefer composition when you only want code reuse. The classic example is a subclass of HashSet that overrides add and addAll to count additions, and gets double counts because addAll calls add internally. Related patterns are in design patterns questions.

Frequently asked questions

Can a constructor be overridden?

No. Constructors are not inherited, so they cannot be overridden, though they can be overloaded within a class.

Why does Java not support multiple inheritance of classes?

To avoid ambiguity and the diamond problem. Interfaces provide multiple type inheritance, and default methods that clash must be resolved explicitly.

What is covariant return type?

An overriding method may return a subtype of the parent method's return type, such as Dog instead of Animal.

Does polymorphism work with fields?

No. Only instance methods dispatch dynamically; field access is resolved from the declared reference type.

Related guides

More in CS Fundamentals Interview Questions

See all in this section