Bird
Raised Fist0

You have a list of Animal objects, some are Dogs and some are Cats. How can polymorphism help you call the correct Speak method for each animal without checking their types?

hard🚀 Application Q8 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
You have a list of Animal objects, some are Dogs and some are Cats. How can polymorphism help you call the correct Speak method for each animal without checking their types?
ABy using if-else statements to check each animal type
BBy making Speak a static method in Animal
CBy casting all animals to Dog before calling Speak
DBy declaring Speak as virtual in Animal and overriding in Dog and Cat
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphic method calls

    Declaring Speak as virtual in base class and overriding in derived classes allows calling correct method via base reference.
  2. Step 2: Avoid type checking

    This removes need for if-else or casting, simplifying code and improving flexibility.
  3. Final Answer:

    By declaring Speak as virtual in Animal and overriding in Dog and Cat -> Option D
  4. Quick Check:

    Virtual + override enables automatic correct method calls [OK]
Quick Trick: Virtual + override calls correct method without type checks [OK]
Common Mistakes:
MISTAKES
  • Using type checks instead of polymorphism
  • Casting incorrectly causing runtime errors
  • Making methods static which disables polymorphism

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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