Safe Downcast with Pattern Matching
mediumQuestion 678Sometimes you must check an object's real type before using a method only the derived class has. The Animal and Dog classes are complete; only Dog has a Fetch() method. In Handler, finish TryFetch(Animal a) so it returns the result of Fetch() when the animal is actually a Dog, and returns Cannot fetch otherwise. Use the type-pattern a is Dog d. Do NOT write a Main method.
For a Dog the program prints the output shown in Expected Output.
For a plain Animal it prints:
Cannot fetch
Expected output
Fetching= newline. The output ends with a newline, so print one after the last line.
Hints4 available
Sign in to use hintsTopics
Polymorphism
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cw, cr, fori)
Your output
Run your code to see the output here...
Test cases
Run your code to see test case results.