Start learning free

LESSON 636 OF 674 · OBJECT-ORIENTED PROGRAMMING

Method Overriding in C#

Lesson

TL ; DR:

When a child class defines a method with the same name as the parent's, the child's version overrides the parent's. Different objects can give the same method name different behavior.


class Dog {
    public virtual void Bark() { Console.WriteLine("Woof!"); }
}
class Puppy : Dog {
    public override void Bark() { Console.WriteLine("Yip!"); }
}


Full lesson:

You've seen that a child class inherits the parent's methods. Overriding is what happens when the child wants to change one of those inherited methods.

Why override?

Subclasses are usually special cases of the parent. A Puppy is a Dog, but it sounds different — "Yip!" instead of "Woof!". Instead of inventing a new method name, you redefine Bark() on the Puppy. Callers don't need to know which subclass they're holding — they just call Bark() and the right version runs.

How it works in C#

The parent method must be marked virtual, and the child marks its replacement override. The compiler enforces this pairing: overriding a method that isn't virtual is a compile error.


Your task

The Dog class already defines Bark. Inside the Puppy subclass, override Bark so it prints "Yip! I am " followed by the puppy's name. The harness creates a Puppy named "Buddy" and calls Bark() on it.

Expected output:

Yip! I am Buddy
STEP 1 OF 2
    Ctrl + Enter to check