Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Java - Polymorphism
Consider this code:
class Fruit { } class Apple extends Fruit { void taste() { System.out.println("Sweet"); } } class Orange extends Fruit { void taste() { System.out.println("Sour"); } } public class Test { public static void main(String[] args) { Fruit f = new Apple(); if (f instanceof Apple) { Apple a = (Apple) f; a.taste(); } else if (f instanceof Orange) { Orange o = (Orange) f; o.taste(); } } }
What concept does this code demonstrate?
ADowncasting with instanceof check
BPolymorphism without casting
CUpcasting without type check
DInvalid casting causing runtime error
Step-by-Step Solution
Solution:
  1. Step 1: Identify use of instanceof

    Code checks object type before downcasting to avoid runtime errors.
  2. Step 2: Confirm safe downcasting

    Downcasting is done only after confirming object is instance of subclass.
  3. Final Answer:

    Downcasting with instanceof check -> Option A
  4. Quick Check:

    Use instanceof to safely downcast [OK]
Quick Trick: Use instanceof to check type before downcasting [OK]
Common Mistakes:
  • Downcasting without instanceof check
  • Confusing polymorphism with casting
  • Expecting automatic safe downcasting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes