Search code examples
javacastingdowncastupcasting

Why downcasting throws ClassCastException in this case?


I have 2 packages: controller and federation. Controller just contains controller class with main method, but federation contains 2 classes, Shuttle (parent class) and MiniShuttle (child class). Upcasting works like a charm, but when I try to downcasting, I get ClassCastException.

This is the code I tried:

Shuttle.java

package federation;

public class Shuttle {

    protected int passengers;

}

MiniShuttle.java

package federation;

public class MiniShuttle extends Shuttle {


}

Controller.java

package controller;

import federation.MiniShuttle;
import federation.Shuttle;

public class Controller {

    public static void main(String[] args) {
        Shuttle shuttle = new Shuttle();
        MiniShuttle mshuttle = (MiniShuttle)shuttle;

        if(mshuttle instanceof Shuttle)
        {
            System.out.println("ok");
        }else
        {
            System.out.println("not ok");
        }

    }

}

Solution

  • Because you have instantiated Shuttle. Declaration new Shuttle() says that object of type Shuttle is instantiated, and a reference to this object is Shuttle (from Shuttle shuttle = ...). If you want to get this to work, use Shuttle shuttle = new MiniShuttle(). With this you are actually saying "I'm instantiating an object of MiniShuttle type and upcasting a reference to it to the type of Shuttle".