December Code

December Code / OOP / polymorphism

Polymorphism interview questions, with answers

Every OOP interview asks about polymorphism, and most candidates give the one-line definition and stop. The marks are in the mechanism: what is decided at compile time and what at run time, why a C++ base pointer calls the wrong method without virtual, and why overloading and overriding are two different things that only sound alike.

Here are the questions with the answers that survive follow-ups, in Java and C++. Then the free OOP diagnostic shows you where you actually stand on it.

The questions, with answers

  1. 1.What is polymorphism, and what are its two kinds?

    Polymorphism means one interface, many implementations: the same call behaves differently depending on the object it's made on. Compile-time (static) polymorphism is resolved by the compiler from the types in the call — method overloading, and operator overloading in C++. Runtime (dynamic) polymorphism is resolved when the program runs, from the actual object's class — method overriding through a base-type reference. When an interviewer asks for "an example of polymorphism", give the runtime one; it is the one that needs inheritance and the one they mean.

    Shape s = new Circle();   // declared type Shape, actual type Circle
    s.area();                 // runs Circle.area() — decided at run time
  2. 2.What is the difference between overloading and overriding?

    Overloading is several methods in the same class with the same name and different parameter lists; the compiler picks one from the argument types at the call site. Overriding is a subclass redefining a method it inherited, with the same signature; the runtime picks the version belonging to the object's actual class. Overloading needs no inheritance and can change the return type freely; overriding needs inheritance and must keep a compatible return type. Overloading is resolved at compile time, overriding at run time — that sentence is usually the whole mark.

  3. 3.How does runtime polymorphism actually work?

    Through dynamic dispatch. In C++, a class with virtual methods gets a virtual table — a per-class array of function pointers — and each object carries a hidden pointer to its class's table; a call through a base pointer looks the method up in the table of the object's real class. In Java every non-static, non-final, non-private method is virtual by default, and the JVM does the equivalent lookup (with heavy optimisation such as inline caches). The consequence to state: the declared type of the variable decides which methods you may call; the runtime type of the object decides which implementation runs.

  4. 4.Why does C++ need the virtual keyword, and what happens without it?

    Without virtual, C++ binds a method call statically to the declared type of the pointer or reference, so Base* p = new Derived(); p->speak() calls Base::speak even though the object is a Derived. Marking speak() virtual in Base switches that call to dynamic dispatch and Derived::speak runs. Java behaves as if every overridable method were virtual, so Java candidates are often surprised by this. The cost of virtual is one pointer per object and an indirect call, which is why C++ makes it opt-in.

    class Base {
    public:
        virtual void speak() { std::cout << "Base"; }
    };
    class Derived : public Base {
    public:
        void speak() override { std::cout << "Derived"; }
    };
    Base* p = new Derived();
    p->speak();   // Derived — remove 'virtual' and it prints Base
  5. 5.Can you overload a method on return type alone?

    No. Two methods with the same name and parameter list but different return types are a compile error in both Java and C++, because the compiler resolves overloads from the arguments at the call site, and a call like f(1) with the result discarded would be ambiguous. Return type does participate in overriding, where a subclass may narrow it (covariant return), but that is a different mechanism.

  6. 6.How does the compiler choose between overloads, and where does it go wrong?

    Java picks the most specific applicable method, in phases: exact or widening primitive matches first, then boxing and unboxing, then varargs. So f(long) is preferred over f(Integer) for an int argument, because widening beats boxing. Ambiguity errors happen when two candidates are equally specific — passing null to f(String) and f(Integer), for instance, since null converts to both and neither is a subtype of the other. The rule to remember: overload resolution uses the declared types of the arguments at compile time, never the runtime type.

    void f(Object o) { }
    void f(String s) { }
    
    Object x = "hello";
    f(x);   // calls f(Object): x is declared Object, even though it holds a String
  7. 7.Are static methods polymorphic?

    No. A static method belongs to the class, not to an instance, so there is no object whose runtime type could be consulted. If a subclass declares a static method with the same signature as one in its superclass, it hides the superclass method rather than overriding it, and which one runs is decided by the declared type of the reference at compile time. The same is true of fields: fields are never overridden, only hidden. Calling a static method through an instance reference compiles in Java but is misleading for exactly this reason.

  8. 8.Why should a C++ base class with virtual methods have a virtual destructor?

    Because deleting a derived object through a base pointer — delete p where p is a Base* — calls only Base's destructor unless the destructor is virtual. The derived part is never destroyed, its resources leak, and the standard says the behaviour is undefined. Declaring virtual ~Base() makes the destructor call dispatch dynamically, so Derived's destructor runs first and then Base's. The rule of thumb interviewers want: if a class has any virtual function, give it a virtual destructor.

How the diagnostic asks it

One question from the OOP bank, exactly as a sitting would show it. The bank has 3 on polymorphism and 30 across OOP.

Polymorphism · easyOOP-005

What does 'polymorphism' mean in OOP?

  1. 1The ability of an object or method to take on many forms, allowing the same interface to behave differently in different contexts.correct
  2. 2The ability to hide an object's internal implementation from other classes.
  3. 3The ability of a class to inherit from more than one parent class.
  4. 4The ability to declare a variable without specifying its data type.

Polymorphism allows the same method call or interface to produce different behavior depending on the object or arguments involved (e.g., overriding and overloading). Option B is encapsulation, option C is multiple inheritance, and option D describes dynamic/loose typing, unrelated to polymorphism specifically.

Measure it

Reading answers tells you what’s true. A diagnostic tells you what you get wrong.

10 OOP questions across its topics, easy to hard, about fifteen minutes. You get a readiness figure with the arithmetic shown, the topics you missed named, and a practice set sized for today. Free: 1 diagnostic a month and 15 problems a day. No card.