Bird
0
0

Given these classes:

hard📝 Application Q8 of 15
Java - Polymorphism
Given these classes:
class Appliance { void powerOn() { System.out.println("Appliance powered on"); } }
class WashingMachine extends Appliance { void powerOn() { System.out.println("Washing machine powered on"); } void startWash() { System.out.println("Washing started"); } }
How can you invoke startWash() on an Appliance reference that actually points to a WashingMachine object?
ACall startWash() directly on the Appliance reference
BCast the Appliance reference to WashingMachine and then call startWash()
CCreate a new WashingMachine object and call startWash() on it
DOverride startWash() in Appliance class
Step-by-Step Solution
Solution:
  1. Step 1: Understand reference type

    An Appliance reference cannot call subclass-specific methods directly.
  2. Step 2: Use downcasting

    Cast the Appliance reference to WashingMachine to access startWash().
  3. Step 3: Correct syntax

    ((WashingMachine) applianceRef).startWash();
  4. Final Answer:

    Cast the Appliance reference to WashingMachine and then call startWash() -> Option B
  5. Quick Check:

    Subclass methods require downcast from superclass reference [OK]
Quick Trick: Downcast superclass ref to subclass to access subclass methods [OK]
Common Mistakes:
  • Calling subclass method on superclass reference without cast
  • Creating new object unnecessarily
  • Trying to override non-existent methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes