Bird
Raised Fist0
Javaprogramming~20 mins

Upcasting and downcasting in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Casting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Upcasting and Method Calls
What is the output of this Java code snippet?
Java
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}
class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
    void fetch() {
        System.out.println("Dog fetches ball");
    }
}
public class Test {
    public static void main(String[] args) {
        Animal a = new Dog(); // upcasting
        a.sound();
    }
}
AAnimal sound
BDog fetches ball
CDog barks
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Remember that overridden methods use the actual object's method, even if referenced by a parent type.
❓ Predict Output
intermediate
2:00remaining
Downcasting and Method Access
What will be the output of this Java code?
Java
class Vehicle {
    void start() {
        System.out.println("Vehicle started");
    }
}
class Car extends Vehicle {
    void openSunroof() {
        System.out.println("Sunroof opened");
    }
}
public class Test {
    public static void main(String[] args) {
        Vehicle v = new Car(); // upcasting
        ((Car) v).openSunroof(); // downcasting
    }
}
ASunroof opened
BVehicle started
CClassCastException at runtime
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Downcasting allows access to subclass-specific methods.
❓ Predict Output
advanced
2:00remaining
Runtime Error from Invalid Downcasting
What error does this code produce when run?
Java
class Fruit {
    void eat() {
        System.out.println("Eating fruit");
    }
}
class Apple extends Fruit {
    void peel() {
        System.out.println("Peeling apple");
    }
}
class Orange extends Fruit {
    void peel() {
        System.out.println("Peeling orange");
    }
}
public class Test {
    public static void main(String[] args) {
        Fruit f = new Orange();
        Apple a = (Apple) f; // downcasting
        a.peel();
    }
}
AClassCastException at runtime
BPeeling orange
CPeeling apple
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Downcasting to a wrong subclass causes runtime errors.
🧠 Conceptual
advanced
2:00remaining
Understanding Upcasting Behavior
Given the code below, what will be the output when main runs?
Java
class Parent {
    void show() {
        System.out.println("Parent show");
    }
}
class Child extends Parent {
    void show() {
        System.out.println("Child show");
    }
    void play() {
        System.out.println("Child play");
    }
}
public class Test {
    public static void main(String[] args) {
        Parent p = new Child(); // upcasting
        p.show();
        // p.play(); // commented out
    }
}
AParent show
BChild show
CChild play
DCompilation error due to p.play()
Attempts:
2 left
πŸ’‘ Hint
Upcasting hides subclass-only methods but overridden methods run subclass versions.
❓ Predict Output
expert
3:00remaining
Output and Behavior of Complex Casting
What is the output of this Java program?
Java
class A {
    void m() {
        System.out.println("A.m()");
    }
}
class B extends A {
    void m() {
        System.out.println("B.m()");
    }
    void n() {
        System.out.println("B.n()");
    }
}
class C extends B {
    void m() {
        System.out.println("C.m()");
    }
    void n() {
        System.out.println("C.n()");
    }
}
public class Test {
    public static void main(String[] args) {
        A obj = new C(); // upcasting
        obj.m();
        ((B) obj).n(); // downcasting
    }
}
ACompilation error
BC.m()\nB.n()
CA.m()\nB.n()
DC.m()\nC.n()
Attempts:
2 left
πŸ’‘ Hint
Method calls use the actual object's version, even after casting.

Practice

(1/5)
1. What is upcasting in Java?
Upcasting means:
easy
A. Changing the value of a variable
B. Treating a specific object as a more general type
C. Creating a new object from a class
D. Converting a general type to a specific type

Solution

  1. Step 1: Understand object type hierarchy

    In Java, classes can inherit from other classes, making some types more general (superclass) and others more specific (subclass).
  2. Step 2: Define upcasting

    Upcasting means treating a subclass object as if it were an instance of its superclass, which is more general.
  3. Final Answer:

    Treating a specific object as a more general type -> Option B
  4. Quick Check:

    Upcasting = Treat specific as general [OK]
Hint: Upcasting = subclass object as superclass type [OK]
Common Mistakes:
  • Confusing upcasting with downcasting
  • Thinking upcasting creates a new object
  • Believing upcasting changes the actual object type
2. Which of the following is the correct syntax for downcasting in Java?
Animal a = new Dog();
// Downcast here
easy
A. Dog d = (Dog) a;
B. Dog d = a;
C. Dog d = a.toDog();
D. Dog d = (Animal) a;

Solution

  1. Step 1: Understand downcasting syntax

    Downcasting requires an explicit cast to convert a superclass reference back to a subclass type.
  2. Step 2: Apply correct cast

    The correct syntax is: SubclassType var = (SubclassType) superClassVar; so here: Dog d = (Dog) a;
  3. Final Answer:

    Dog d = (Dog) a; -> Option A
  4. Quick Check:

    Downcasting needs explicit cast [OK]
Hint: Downcast with (Subclass) before variable [OK]
Common Mistakes:
  • Omitting the cast operator
  • Casting to wrong type
  • Using methods like toDog() which don't exist
3. What will be the output of this code?
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.println("Bark"); } void fetch() { System.out.println("Fetching"); } }
public class Test {
  public static void main(String[] args) {
    Animal a = new Dog(); // upcasting
    a.sound();
    // a.fetch(); // line A
    ((Dog) a).fetch(); // line B
  }
}
medium
A. Bark\nFetching
B. Bark\nAnimal sound
C. Animal sound\nFetching
D. Compilation error at line A

Solution

  1. Step 1: Understand method overriding and upcasting

    Variable a is of type Animal but refers to a Dog object. Calling a.sound() calls Dog's overridden method, printing "Bark".
  2. Step 2: Analyze method call fetch()

    Method fetch() is not in Animal, so a.fetch() is invalid (commented out). Downcasting (Dog) a allows calling fetch(), printing "Fetching".
  3. Final Answer:

    Bark Fetching -> Option A
  4. Quick Check:

    Upcast calls overridden method, downcast calls subclass method [OK]
Hint: Upcast calls overridden; downcast needed for subclass-only methods [OK]
Common Mistakes:
  • Thinking a.sound() calls Animal's method
  • Trying to call fetch() without downcasting
  • Confusing compile vs runtime errors
4. Identify the error and fix it in this code:
class Animal {}
class Cat extends Animal { void meow() { System.out.println("Meow"); } }
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    Cat c = (Cat) a; // line X
    c.meow();
  }
}
medium
A. No error, code runs fine
B. Syntax error; fix by removing cast
C. ClassCastException at runtime; fix by checking instanceof before casting
D. Change Animal to Cat in line X

Solution

  1. Step 1: Identify the casting problem

    Variable a refers to an Animal object, not a Cat. Casting Animal to Cat without checking causes ClassCastException at runtime.
  2. Step 2: Fix with instanceof check

    Before casting, check if (a instanceof Cat) to ensure safe downcasting and avoid runtime error.
  3. Final Answer:

    ClassCastException at runtime; fix by checking instanceof before casting -> Option C
  4. Quick Check:

    Downcast only if instanceof true [OK]
Hint: Use instanceof before downcasting to avoid errors [OK]
Common Mistakes:
  • Ignoring runtime ClassCastException
  • Assuming cast always works
  • Trying to fix with syntax changes only
5. Given these classes:
class Vehicle { void start() { System.out.println("Vehicle started"); } }
class Car extends Vehicle { void start() { System.out.println("Car started"); } void openTrunk() { System.out.println("Trunk opened"); } }
class Bike extends Vehicle { void start() { System.out.println("Bike started"); } void kickStart() { System.out.println("Kickstarted"); } }

Which code snippet correctly upcasts and downcasts to call openTrunk() safely?
hard
A.
Vehicle v = new Vehicle();
if (v instanceof Car) {
  ((Car) v).openTrunk();
}
B.
Vehicle v = new Bike();
((Car) v).openTrunk();
C.
Car c = new Vehicle();
c.openTrunk();
D.
Vehicle v = new Car();
if (v instanceof Car) {
  ((Car) v).openTrunk();
}

Solution

  1. Step 1: Understand upcasting and downcasting here

    Variable v is declared as Vehicle but assigned a Car object (upcasting). To call Car-specific method openTrunk(), downcast is needed.
  2. Step 2: Check safe downcasting

    Using instanceof ensures v is actually a Car before downcasting and calling openTrunk(). This avoids runtime errors.
  3. Final Answer:

    Vehicle v = new Car(); if (v instanceof Car) { ((Car) v).openTrunk(); } -> Option D
  4. Quick Check:

    Upcast then instanceof check before downcast [OK]
Hint: Always check instanceof before downcasting [OK]
Common Mistakes:
  • Downcasting without instanceof check
  • Assigning superclass object to subclass variable
  • Calling subclass methods on superclass references without cast