CJCoding With Joseph
15free / daySign inCreate account

Safe Downcast with Pattern Matching

Sometimes 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 — print one after the last line.

Hints4 available
Topics:
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.