โ Back to Polymorphism
Question 588
Safe Downcast with Pattern Matching
Safe Downcast with Pattern Matching
Sometimes you must check an object's real type before using a method only the derived class has. TheAnimalandDogclasses are complete; onlyDoghas aFetch()method. InHandler, finishTryFetch(Animal a)so it returns the result ofFetch()when the animal is actually aDog, and returnsCannot fetchotherwise. Use the type-patterna is Dog d. Do NOT write aMainmethod. For aDogthe program prints: Fetching For a plainAnimalit prints: Cannot fetch
Expected Output:
Fetching
Topics:
Polymorphism
Code Editor
1
Tab to indent ยท Ctrl+Enter to run ยท 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.