Bird
0
0

Consider the following C# code:

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
Consider the following C# code:
class Animal { public virtual string Speak() => "..."; }
class Dog : Animal { public override string Speak() => "Woof"; }
class Cat : Animal { public override string Speak() => "Meow"; }

Animal a = new Dog();
Console.WriteLine(a.Speak());

What is the output?
AWoof
B...
CMeow
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphism with virtual and override

    The variable 'a' is of type Animal but holds a Dog object. The Speak method is virtual and overridden in Dog.
  2. Step 2: Determine which Speak method runs

    At runtime, the Dog's Speak method runs, returning "Woof".
  3. Final Answer:

    Woof -> Option A
  4. Quick Check:

    Virtual method calls overridden version [OK]
Quick Trick: Virtual method calls override in actual object type [OK]
Common Mistakes:
MISTAKES
  • Expecting base class method output
  • Confusing variable type with object type
  • Thinking code causes compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes