override versus new (method hiding)

A favourite interview question: what prints when a derived object is used through a base-type variable?

Time O(1)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

override replaces the base method for the object, whatever variable it is seen through. new only hides the base method: which one you get depends on the type of the variable you call it on.

Code

Base x = new Derived();
Console.WriteLine(x.Who());   // Derived: uses the object's type
Console.WriteLine(x.Tag());   // Base: uses the variable's type
Derived y = (Derived)x;
Console.WriteLine(y.Tag());   // Derived

class Base {
    public virtual string Who() => "Base";
    public string Tag() => "Base";
}
class Derived : Base {
    public override string Who() => "Derived";
    public new string Tag() => "Derived";     // hides, does not override
}
class Base {
    String who() { return "Base"; }
    static String tag() { return "Base"; }
}
class Derived extends Base {
    @Override String who() { return "Derived"; }
    static String tag() { return "Derived"; }     // hides, does not override (only static methods can hide)
}

public class Main {
    public static void main(String[] args) {
        Base x = new Derived();
        System.out.println(x.who());   // Derived: uses the object's type
        System.out.println(x.tag());   // Base: uses the variable's type
        Derived y = (Derived) x;
        System.out.println(y.tag());   // Derived
    }
}
class Base {
public:
    virtual string who() const { return "Base"; }
    string tag() const { return "Base"; }
    virtual ~Base() = default;
};
class Derived : public Base {
public:
    string who() const override { return "Derived"; }
    string tag() const { return "Derived"; }     // hides, does not override
};

int main() {
    unique_ptr<Base> x = make_unique<Derived>();
    cout << x->who() << "\n";   // Derived: uses the object's type
    cout << x->tag() << "\n";   // Base: uses the variable's type
    Derived* y = static_cast<Derived*>(x.get());
    cout << y->tag() << "\n";   // Derived
}
class Base:
    def who(self) -> str: return "Base"
    def tag(self) -> str: return "Base"

class Derived(Base):
    def who(self) -> str: return "Derived"
    def tag(self) -> str: return "Derived"  # Python cannot hide: every method overrides

x: Base = Derived()
print(x.who())  # Derived: uses the object's type
print(Base.tag(x))  # Base: only by naming the class explicitly
y: Derived = x
print(y.tag())  # Derived

Tips

In the .NET library

Interface members and abstract members are always dispatched on the object. Marking an override as sealed override stops further overriding below that class.